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
上一篇:浏览器(Cache)的缓存逻辑(HTTP条件请求)


下一篇:Usage of API documented as @since 1.8+ less... (Ctrl+F1) Inspection info: This inspection finds all