如何在 python 中测量已过去的时间?
要测量程序执行期间的已过去时间,可以使用 time.clock() 或 time.time() 函数。python 文档指出,此函数应用于基准测试。
示例
import time t0= time.clock() print("Hello") t1 = time.clock() - t0 print("Time elapsed: ", t1) # CPU seconds elapsed (floating point)
输出
这将产生以下输出 −
Time elapsed: 1.2999999999999123e-05
你还可以使用 time 模块根据代码段的执行时间获取适当的统计分析。 它会多次运行代码段,然后告诉你最短运行时间。你可以按照以下方法使用它
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例
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]
广告