ZetCode

Python time.thread_time 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨 Python 的 time.thread_time 函数,该函数返回当前线程的 CPU 时间。我们将涵盖线程特定的计时、性能测量和实际示例。

基本定义

time.thread_time 函数以秒为单位返回当前线程的 CPU 时间,以浮点数表示。 它测量在当前线程中执行所花费的时间。

主要特征:线程特定的 CPU 时间,不包括睡眠时间,可用于性能分析。 参考点未定义,因此只有差异才有意义。

基本线程时间测量

此示例显示了 thread_time 的基本用法,用于测量当前线程在计算期间消耗的 CPU 时间。

basic_thread_time.py
import time

def compute():
    sum(range(10**6))  # CPU-intensive work

start = time.thread_time()
compute()
end = time.thread_time()

print(f"CPU time used: {end - start:.6f} seconds")

这仅测量当前线程中花费的 CPU 时间。 睡眠时间或其他线程的工作不会影响测量。

精度取决于平台,但通常为纳秒级。 只能比较时间差。

比较线程时间与进程时间

此示例将 thread_timeprocess_time 进行比较,以显示线程特定的 CPU 时间测量与进程范围的 CPU 时间测量。

thread_vs_process.py
import time
import threading

def worker():
    start_thread = time.thread_time()
    start_process = time.process_time()
    
    sum(range(10**7))  # CPU work
    
    end_thread = time.thread_time()
    end_process = time.process_time()
    
    print(f"Thread CPU: {end_thread - start_thread:.3f}s")
    print(f"Process CPU: {end_process - start_process:.3f}s")

# Create and start two threads
t1 = threading.Thread(target=worker)
t2 = threading.Thread(target=worker)
t1.start()
t2.start()
t1.join()
t2.join()

thread_time 仅测量调用线程的 CPU 时间,而 process_time 包括进程中的所有线程。

在分析多线程应用程序时,这种区别至关重要。

测量 I/O 密集型操作与 CPU 密集型操作

此示例演示了 thread_time 如何区分线程中的 CPU 密集型操作和 I/O 密集型操作。

io_vs_cpu.py
import time

def mixed_work():
    # CPU-bound work
    start_cpu = time.thread_time()
    sum(range(10**6))
    end_cpu = time.thread_time()
    
    # I/O-bound work (sleep simulates waiting)
    start_io = time.thread_time()
    time.sleep(1)
    end_io = time.thread_time()
    
    print(f"CPU work time: {end_cpu - start_cpu:.6f}s")
    print(f"I/O wait time: {end_io - start_io:.6f}s")

mixed_work()

睡眠时间不计入线程 CPU 时间,这表明 thread_time 仅测量实际 CPU 使用率。

这有助于识别线程是 CPU 密集型还是等待 I/O 操作。

分析函数执行

此示例创建一个装饰器,该装饰器使用 thread_time 分析函数,以测量其 CPU 消耗。

profiler.py
import time

def profile(func):
    def wrapper(*args, **kwargs):
        start = time.thread_time()
        result = func(*args, **kwargs)
        end = time.thread_time()
        print(f"{func.__name__} used {end - start:.6f}s CPU time")
        return result
    return wrapper

@profile
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

@profile
def sleep_and_compute():
    time.sleep(0.5)
    sum(range(10**6))

factorial(10)
sleep_and_compute()

装饰器仅测量函数使用的 CPU 时间,不包括任何等待时间或其他线程中的时间。

这对于识别多线程应用程序中的 CPU 密集型函数特别有用。

比较线程性能

此示例使用 thread_time 比较同一任务的不同线程实现的 CPU 消耗。

thread_comparison.py
import time
import threading

def worker_optimized():
    start = time.thread_time()
    # Efficient computation
    sum(i*i for i in range(10**6))
    end = time.thread_time()
    print(f"Optimized: {end - start:.6f}s")

def worker_unoptimized():
    start = time.thread_time()
    # Less efficient computation
    total = 0
    for i in range(10**6):
        total += i*i
    end = time.thread_time()
    print(f"Unoptimized: {end - start:.6f}s")

t1 = threading.Thread(target=worker_optimized)
t2 = threading.Thread(target=worker_unoptimized)
t1.start()
t2.start()
t1.join()
t2.join()

通过分别测量每个线程的 CPU 时间,我们可以比较并发运行的不同实现的效率。

这种方法有助于识别多线程代码中的性能优化。

随着时间的推移监控线程 CPU 使用率

此示例演示如何使用 thread_time 通过定期采样来监控线程随时间的 CPU 使用率。

monitoring.py
import time
import threading

def worker():
    last_time = time.thread_time()
    for i in range(5):
        # Do some work
        sum(range(10**6))
        
        current_time = time.thread_time()
        cpu_used = current_time - last_time
        print(f"Interval {i}: {cpu_used:.3f}s CPU time")
        last_time = current_time
        
        # Simulate mixed workload
        time.sleep(0.2)

thread = threading.Thread(target=worker)
thread.start()
thread.join()

通过进行定期测量,我们可以跟踪线程执行期间 CPU 使用率的变化情况。

此技术对于识别长时间运行的线程中 CPU 使用率高的阶段很有用。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程