ZetCode

Python time.process_time 函数

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

本综合指南探讨了 Python 的 time.process_time 函数,该函数返回当前进程使用的 CPU 时间。我们将涵盖 CPU 时间测量、性能基准测试和实际计时示例。

基本定义

time.process_time 函数将当前 CPU 时间作为以秒表示的浮点数返回。 它测量系统和用户 CPU 时间。

主要特点:仅测量进程 CPU 时间(不测量睡眠时间)、平台相关的精度,并且可用于 CPU 密集型性能测量。 返回值是一个浮点数,用于表示亚秒级精度。

基本 CPU 时间测量

time.process_time 最简单的用法是测量已使用的 CPU 时间。 此示例显示了基本用法以及与挂钟时间的比较。

basic_process_time.py
import time

# Get current CPU time
cpu_start = time.process_time()

# Perform CPU-bound work
sum(range(10000000))

cpu_end = time.process_time()
print(f"CPU time used: {cpu_end - cpu_start:.4f} seconds")

# Compare with wall-clock time
wall_start = time.time()
sum(range(10000000))
wall_end = time.time()
print(f"Wall-clock time: {wall_end - wall_start:.4f} seconds")

此示例演示了测量 CPU 时间与挂钟时间。 只有当进程主动使用 CPU 时,才会计入 CPU 时间。

该差异显示了花费在等待而不是计算上的时间。 这对于性能优化很有用。

测量函数 CPU 时间

time.process_time 非常适合测量 CPU 密集型函数的性能。 此示例演示如何对 CPU 密集型函数进行计时。

function_timing.py
import time

def cpu_intensive_task():
    result = 0
    for i in range(10000000):
        result += i * i
    return result

# Start CPU timer
start_cpu = time.process_time()

# Execute CPU-bound function
result = cpu_intensive_task()

# Calculate CPU duration
end_cpu = time.process_time()
cpu_duration = end_cpu - start_cpu

print(f"Function result: {result}")
print(f"CPU time used: {cpu_duration:.6f} seconds")

此模式测量实际 CPU 使用率,忽略任何等待时间。 它非常适合优化 CPU 密集型算法。

process_time 的精度使其适用于微基准测试紧密循环和数学运算。

比较 CPU 时间与挂钟时间

此示例演示了当涉及睡眠操作时,CPU 时间和挂钟时间之间的差异。

sleep_comparison.py
import time

def mixed_operation():
    # CPU-bound work
    sum(range(1000000))
    # I/O-bound wait
    time.sleep(1)
    # More CPU work
    sum(range(1000000))

# CPU time measurement
cpu_start = time.process_time()
mixed_operation()
cpu_end = time.process_time()
print(f"CPU time: {cpu_end - cpu_start:.4f} sec")

# Wall time measurement
wall_start = time.time()
mixed_operation()
wall_end = time.time()
print(f"Wall time: {wall_end - wall_start:.4f} sec")

process_time 忽略睡眠时间,而 time.time 测量总经过时间。 这表明 I/O 如何影响性能。

对于 CPU 密集型优化,请关注 CPU 时间。 对于整体性能,请同时考虑这两个指标。

分析多个操作

此示例使用 process_time 来分析不同的操作并比较它们的 CPU 使用率。

profiling.py
import time
import math

def measure_operation(op, name):
    start = time.process_time()
    op()
    duration = time.process_time() - start
    print(f"{name}: {duration:.6f} sec")

# Define operations
def list_comp():
    [x*x for x in range(1000000)]

def map_lambda():
    list(map(lambda x: x*x, range(1000000)))

def math_operations():
    for x in range(10000):
        math.sin(x) + math.cos(x)

# Profile each operation
measure_operation(list_comp, "List comprehension")
measure_operation(map_lambda, "Map with lambda")
measure_operation(math_operations, "Math functions")

此技术有助于识别代码中 CPU 密集型操作。 结果可以指导优化工作。

请注意,绝对时间可能因运行而异,但相对比较对于优化仍然有意义。

跟踪累积 CPU 时间

此示例演示了跨多个函数调用或迭代跟踪累积 CPU 时间。

cumulative_time.py
import time
import random

def process_data(data):
    # Simulate variable CPU load
    time.sleep(random.random() * 0.1)
    return sum(x*x for x in data)

total_cpu = 0.0
data_sets = [list(range(i, i+10000)) for i in range(0, 100000, 10000)]

for data in data_sets:
    cpu_start = time.process_time()
    result = process_data(data)
    cpu_end = time.process_time()
    total_cpu += cpu_end - cpu_start
    print(f"Processed set, result: {result}")

print(f"\nTotal CPU time: {total_cpu:.4f} seconds")
print(f"Average per set: {total_cpu/len(data_sets):.6f} seconds")

跟踪累积 CPU 时间有助于识别跨多个操作或数据集的性能趋势。

此模式对于批量处理系统很有用,在这些系统中,了解总资源使用情况非常重要。

比较算法

此示例使用 process_time 来比较解决相同问题的不同算法的 CPU 效率。

algorithm_comparison.py
import time

def factorial_recursive(n):
    return 1 if n <= 1 else n * factorial_recursive(n-1)

def factorial_iterative(n):
    result = 1
    for i in range(1, n+1):
        result *= i
    return result

def measure_factorial(func, n, name):
    start = time.process_time()
    result = func(n)
    duration = time.process_time() - start
    print(f"{name} ({n}): {duration:.6f} sec")
    return result

n = 900
rec_result = measure_factorial(factorial_recursive, n, "Recursive")
iter_result = measure_factorial(factorial_iterative, n, "Iterative")

assert rec_result == iter_result

CPU 时间测量为算法选择提供了客观数据。 此示例比较了递归与迭代阶乘实现。

在优化关键代码路径时,这种比较非常有价值,因为效率上的微小差异很重要。

随时间推移监控 CPU 使用率

此示例演示了如何通过按间隔采样来监控长时间运行的操作期间的 CPU 使用率模式。

cpu_monitoring.py
import time
import random

def long_running_task():
    # Simulate mixed CPU and I/O workload
    for i in range(10):
        # CPU-intensive phase
        start_phase = time.process_time()
        sum(x*x for x in range(1000000 * (i+1)))
        cpu_time = time.process_time() - start_phase
        
        # Report phase statistics
        print(f"Phase {i+1}: CPU time {cpu_time:.3f} sec")
        
        # Simulate I/O wait
        time.sleep(random.random())

# Start monitoring
print("Starting task monitoring...")
start_total = time.process_time()
long_running_task()
total_cpu = time.process_time() - start_total

print(f"\nTotal CPU time: {total_cpu:.3f} seconds")

此技术有助于识别长时间运行的进程中 CPU 密集型活动的阶段。 数据可以指导优化工作。

通过按阶段细分 CPU 使用率,您可以将优化工作重点放在影响最大的地方。

最佳实践

资料来源

作者

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

列出所有 Python 教程