5种方法对python程序代码做性能分析和计时统计

python代码运行时间统计

以下4种方法分别针对 代码块、代码程序文件、 函数 进行性能计时统计

  • time.time()
  • time.clock() /time.perf_counter()
  • time命令
  • timeit模块
  • timethis装饰器

time.time()

返回当前时间的时间戳 如 1524302633.980187
两次时间相减,代码运行所需的 挂钟时间,也就是命令开始执行到结束的时间。

import time
start = time.time()
print("Hello World")
time.sleep(2)
end = time.time()
print(end - start)

输出

Hello World
2.0038700103759766

time.clock()

clock() 函数以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。
在win系统下,这个函数返回的是真实时间(wall time),而在Unix/Linux下返回的是CPU时间。

#文件 test.py
import time
start = time.clock()
print("Hello World")
time.sleep(2)
end = time.clock()
print(end - start)

linux 下输出

Hello World
0.00020299999999999485

time.clock(),python 3.3版本以后这个函数被废弃了,但是这个函数仍然可以使用。

time–对脚本文件运行时间进行计时统计

在linux下对整个程序做计时统计

time python test.py

运行多次取平均时间
输出内容
real 0m2.057s
user 0m0.033s
sys 0m0.011s

real 脚本开始运行到结束的时间,包括其他进程运行占用的时间。time.sleep(2) 时间算在内。
user 用于执行进程所花费的时间,其他进程和花费阻塞状态中的时间没有计算在内。
sys 进程使用的CPU时间

更详细的报告

python -m cProfile test.py

Hello World
0.00010600000000000193
         8 function calls in 2.005 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.005    2.005 test.py:3(<module>)
        1    0.000    0.000    2.005    2.005 {built-in method builtins.exec}
        2    0.000    0.000    0.000    0.000 {built-in method builtins.print}
        2    0.000    0.000    0.000    0.000 {built-in method time.clock}
        1    2.005    2.005    2.005    2.005 {built-in method time.sleep}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

timeit–对小段代码做性能统计

from timeit import timeit

timeit('math.sqrt(2)', 'import math', number=100000)

装饰器–对函数进行计时统计

定义装饰器timethis
将装饰器放在函数定义之前,就能得到对应函数的计时信息

from functools import wraps
import time

def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        r = func(*args, **kwargs)
        end = time.perf_counter()
        print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
        return r
    return wrapper

@timethis
def ts():
    time.sleep(2)
    print("Hello World")

ts()

输出
Hello World
main.ts : 2.0007375059940387

备注

使用time.perf_counter() 能够提供给定平台上精度最高的计时器,但是,它计算的仍然是时钟时间,很多因素会影响到它的精确度,比如机器负载。
如果你对于执行时间更感兴趣,使用time.process_time() 来代替它。

猜你喜欢

转载自blog.csdn.net/lhh08hasee/article/details/80032193