Python中测量经过时间的方法

Python中测量经过时间的方法

技术背景

在Python开发中,我们经常需要测量一段代码或一个函数的执行时间,以此来评估代码的性能、优化算法或者比较不同实现方式的效率。Python提供了多种方法来实现时间测量,每种方法都有其特点和适用场景。

实现步骤

1. 使用time.time()

time.time()返回当前时间的时间戳(从纪元开始的秒数),可以通过记录开始和结束的时间戳来计算经过的时间。

1
2
3
4
5
6
import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

这种方法简单直接,能得到代码执行的大致时间,但它受系统时间调整的影响,如NTP时间同步、手动调整系统时间等。

2. 使用timeit.default_timer

timeit.default_timer会根据不同的操作系统和Python版本自动选择最佳的时钟,在Python 3.3+中,它被赋值为time.perf_counter()

1
2
3
4
5
6
from timeit import default_timer as timer

start = timer()
# ...
end = timer()
print(end - start)

这种方法相对准确,能避免一些系统时间调整带来的问题。

3. 使用time.perf_counter()time.process_time()(Python 3)

  • time.perf_counter():用于系统范围的计时,返回性能计数器的值,包括睡眠时间,具有较高的精度。
1
2
3
4
5
import time

t = time.perf_counter()
# do some stuff
elapsed_time = time.perf_counter() - t
  • time.process_time():用于进程范围的计时,不包括睡眠时间,只统计CPU的执行时间。
1
2
3
4
5
import time

t = time.process_time()
# do some stuff
elapsed_time = time.process_time() - t

4. 使用timeit模块

timeit模块可以更精确地测量代码的执行时间,它会多次执行代码并计算平均时间。

1
2
3
4
5
6
7
import timeit

def foo():
return 1 + 1

time = timeit.timeit(foo, number=1000)
print(time)

从命令行使用timeit

1
python -mtimeit -s'import test' 'test.foo()'

5. 使用上下文管理器

可以自定义上下文管理器来方便地测量代码块的执行时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from contextlib import contextmanager
from timeit import default_timer

@contextmanager
def elapsed_timer():
start = default_timer()
elapser = lambda: default_timer() - start
yield lambda: elapser()
end = default_timer()
elapser = lambda: end - start

import time

with elapsed_timer() as elapsed:
time.sleep(1)
print(elapsed())
time.sleep(2)
print(elapsed())
time.sleep(3)

6. 使用装饰器

可以定义装饰器来测量函数的执行时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import time

def timing_decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
original_return_val = func(*args, **kwargs)
end = time.perf_counter()
print("time elapsed in ", func.__name__, ": ", end - start, sep='')
return original_return_val

return wrapper

@timing_decorator
def function_to_time():
time.sleep(1)

function_to_time()

核心代码示例

使用time.perf_counter()测量函数执行时间

1
2
3
4
5
6
7
8
9
10
import time

def my_function():
for i in range(1000000):
pass

start = time.perf_counter()
my_function()
end = time.perf_counter()
print(f"函数执行时间: {end - start} 秒")

使用timeit模块测量代码块执行时间

1
2
3
4
5
6
7
8
9
import timeit

code = """
for i in range(1000):
pass
"""

execution_time = timeit.timeit(code, number=1000)
print(f"代码块执行时间: {execution_time} 秒")

最佳实践

  • 选择合适的方法:根据具体需求选择合适的时间测量方法。如果只需要大致的执行时间,可以使用time.time();如果需要更精确的测量,建议使用timeit模块或time.perf_counter()
  • 多次测量取平均值:为了得到更准确的结果,可以多次执行代码并计算平均时间。timeit模块会自动进行多次执行并计算平均值。
  • 避免干扰因素:在测量时间时,尽量避免其他程序的干扰,确保测量环境稳定。

常见问题

1. 测量结果不准确

  • 原因:系统时间调整、其他程序的干扰、垃圾回收等因素都可能影响测量结果。
  • 解决方法:使用timeit模块,它会自动处理垃圾回收等问题,并多次执行代码取平均值;选择合适的时钟函数,如time.perf_counter(),它受系统时间调整的影响较小。

2. timeit使用复杂

  • 原因timeit需要设置代码和执行次数,对于复杂的代码可能需要额外的设置。
  • 解决方法:可以将代码封装成函数,然后使用timeit测量函数的执行时间;也可以从命令行使用timeit,避免在代码中进行复杂的设置。

3. 测量结果包含睡眠时间

  • 原因:某些时钟函数(如time.perf_counter())会包含睡眠时间。
  • 解决方法:如果不需要包含睡眠时间,可以使用time.process_time()来测量CPU的执行时间。

Python中测量经过时间的方法
https://119291.xyz/posts/2025-04-14.python-measure-elapsed-time-methods/
作者
ww
发布于
2025年4月14日
许可协议