python如何计算程序运算时间
发布时间:2026-05-14 16:03:24

计算python程序运算时间的方法:
方法1:
importdatetime starttime=datetime.datetime.now() #longrunning #dosomethingother endtime=datetime.datetime.now() print(endtime-starttime).seconds
datetime.datetime.now()获得的是当前日期,程序执行完成后,这种方法获得的时间值就是程序执行的时间。
方法2:
start=time.time() #longrunning #dosomethingother end=time.time() printend-start
time.time()获取自时代以来的当前时间(以秒为单位)。如果系统时钟提供它们,可能会有秒的分数。所以这个地方回到了浮点类型。程序的执行时间也在这里获得。
方法3:
start=time.clock() #longrunning #dosomethingother end=time.clock() printend-start
time.clock()CPU时间自返回程序开始或首次调用clock()以来。 这和系统记录一样准确。返回也是一种浮点类型。CPU的执行时间在这里获得。
注:程序执行时间=cpu时间 + io时间 + 休眠或等待时间
请关注Python视频教程栏目,了解更多Python知识。
下一篇 mysql是开源的吗
