编程语言
首页 > 编程语言> > Python中的time.time模块

Python中的time.time模块

作者:互联网

计算代码的运行时间:

1、以分钟和秒为单位
import time

def havefun():
    since = time.time()
    time.sleep(5)  # 睡眠5秒
    time_elapsed = time.time() - since
    print('The code run {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))

havefun()

结果为:

The code run 0m 5s
2、以秒为单位
import time

def add(a, b):
    sum = 0
    for i in range(a):
        for j in range(b):
            sum += 1
    return sum

def havefun():
    since = time.time()
    time.sleep(100)
    s = add(10000, 10000)
    time_elapsed = time.time() - since
    print('The code run {:.0f}s'.format(
            60 * (time_elapsed // 60) + time_elapsed % 60))
    print(s)

havefun()

结果为:

The code run 106s
100000000

标签:code,havefun,Python,since,elapsed,60,模块,time
来源: https://blog.csdn.net/weixin_43283397/article/details/100688741