Python版计算程序运行时间

我以前在C语言中介绍过计算程序运行时间的方法,该计算方法容易理解,具体步骤如下:

1.在程序开始运行前获取当前的时间,并且记录该时间
2.运行某个程序,以便统计该程序的运行时间
3.在程序运行结束后获取当前的时间,并且记录该时间
4.把步骤3和步骤1中记录的时间相减后就是程序的运行时间

我们知道time模块的time()函数具有获取当前时间的功能,使用该函数获取当前时间并且记录就可以。

下面是源代码,请参考:

import time


def func():
    product = 1
    for i in range(1, 3):
        product *= i
        time.sleep(1)
    return product

start = time.time()
res = func()
end = time.time()

print("start time: %d , end time: %d" %(start, end))
print("The result is %d " % res)
print("it  cost %s s for func running " %(end - start))
print("it  cost %s s for func running " %(round((end - start),3)))

在程序中我们使用round()函数对运行结果进行了处理,这样方便阅读。

下面是程序的运行结果:

start time: 1534667088 , end time: 1534667090
The result is 2 
it  cost 2.0001142024993896 s for func running 
it  cost 2.0 s for func running 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

talk_8

真诚赞赏,手有余香

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值