如何在 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]

更新日期:07-06-2020

2K+ 浏览

开启你的 职业生涯

通过完成课程获得证书

开始
广告