如何获取 Python 程序的执行时间?

pythonserver side programmingprogramming更新于 2026/2/2 23:40:17

要测量程序的执行时间,请使用 time.clock() 或 time.time() 函数。 python 文档指出此函数应用于基准测试目的。

示例

import time
t0= time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed: ", t1 - t0) # CPU 已用秒数(浮点数)

输出

将给出输出 −

Time elapsed:  0.0009403145040156798

您还可以使用 timeit 模块对代码片段的执行时间进行适当的统计分析。  它会多次运行该代码段,然后告诉您最短的运行时间。您可以按如下方式使用它 −

示例

def f(x):
  return x * x
 
import timeit
timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)

输出

这将给出输出 −

[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]



相关文章


有用资源