如何测量 Python 函数的执行时间?

102 篇文章 ¥59.90 ¥99.00
本文介绍了在Python中如何使用time模块和timeit模块来测量函数的执行时间。time模块的time()函数适用于简单测量,而timeit模块能提供更精确的多次测量结果,适合复杂场景的性能评估。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 Python 中,我们经常需要评估代码的性能,特别是对于耗时较长的函数。为了测量函数的执行时间,我们可以使用 Python 的内置模块 time 或者第三方库 timeit。下面将介绍这两种方法的用法。

  1. 使用 time 模块

Python 的 time 模块提供了一些函数来测量时间。其中最常用的是 time.time() 函数,它返回当前的系统时间(以秒为单位)。我们可以在函数的开始和结束位置分别调用 time.time(),然后计算两个时间点的差值,即可得到函数的执行时间。

下面是一个示例代码:

import time

def my_function():
    start_time = time
### 测量 Python 函数执行时间 #### 使用 `time` 模块测量函数执行时间 可以使用 Python 内置的 `time` 模块来测量函数执行时间。具体来说,可以在调用目标函数前后分别记录当前时间戳,之后相减得到该函数执行时间。 ```python import time def example_function(): sum = 0 for i in range(1000000): sum += i return sum start_time = time.time() # 获取开始时间 example_function() end_time = time.time() # 获取结束时间 execution_time = end_time - start_time print(f"Execution Time: {execution_time} seconds") # 输出执行时间[^1] ``` #### 利用 `timeit` 模块更精确地测量 对于更加精准的结果,推荐采用 `timeit` 模块来进行多次重复实验取平均值的方式,从而减少偶然误差的影响。 ```python from timeit import default_timer as timer def another_example_function(): product = 1 for j in range(1, 10000): product *= j return product repeat_times = 7 total_duration = 0.0 for _ in range(repeat_times): begin = timer() another_example_function() finish = timer() total_duration += (finish-begin) average_execution_time = total_duration / repeat_times print(f'Average Execution Time over {repeat_times} runs is {average_execution_time:.8f} seconds') ``` #### 应用装饰器简化计时流程 为了使代码更为简洁易读,还可以定义一个通用的装饰器用于自动包裹任何待测函数,在每次被调用前启动定时器并在完成后停止并打印消耗掉的时间长度。 ```python import functools import time def timing_decorator(func): @functools.wraps(func) def wrapper(*args,**kwargs): start_tick = time.perf_counter() result=func(*args,**kwargs) elapsed=(time.perf_counter()-start_tick)*1e3 print(f"{func.__name__!r} took {elapsed:.4f} ms to complete.") return result return wrapper @timing_decorator def sample_function(x,y,z): """A simple function that multiplies three numbers.""" return x*y*z sample_result = sample_function(2,3,4) # Output will look like this: # 'sample_function' took X.XXXX ms to complete. ``` [^5]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值