您的位置:首页 > 编程语言 > Python开发

转 Python获取代码运行时间的几种方法

2018-11-14 13:56 197 查看
版权声明: https://blog.csdn.net/asialee_bird/article/details/79673860 Python获取代码运行时间的几种方法1、方法一:#python 的标准库手册推荐在任何情况下尽量使用time.clock().#只计算了程序运行CPU的时间,返回值是浮点数import timestart =time.clock()#中间写上代码块end = time.clock()print('Running time: %s Seconds'%(end-start))
#运行结果如下#Running time: 2.26660703157 Seconds
2、方法二:#该方法包含了其他程序使用CPU的时间,返回值是浮点数import timestart=time.time()#中间写上代码块end=time.time()print('Running time: %s Seconds'%(end-start))
#运行结果#Running time: 4.90400004387 Seconds
3、方法三:#该方法包含了其他程序使用CPU的时间import datetimestart=datetime.datetime.now()#中间写代码块end=datetime.datetime.now()print('Running time: %s Seconds'%(end-start))
#运行结果#Running time: 0:00:02.412000 Seconds
4、方法四:# Unix 系统中,建议使用 time.time(),在 Windows 系统中,建议使用 time.clock()
#实现跨平台的精度性可以使用timeit.default_timer()import timeitstart=timeit.default_timer()#中间写代码块end=timeit.default_timer()print('Running time: %s Seconds'%(end-start))
#运行结果#Running time: 2.31757675399 Seconds


注释:以上四种代码运行环境是Win7系统,都是在相同的代码块下运行的,可以对比代码运行时间获取windows系统下的最优方法;对于其他系统可以进行测试获取最优方法!











阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: