对python代码进行性能测试

1,使用装饰器:

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 coundown(n):
    while n > 0:
        n = -1
coundown(100000000000000000)

2.使用上下文管理器对代码片段进行测试:

from contextlib import contextmanager
@contextmanager
def timeblock(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        end = time.perf_counter()
        print('{}:{}'.format(label,end - start))

with timeblock('counting'):
    n = 10000000
    while n> 0 :
        n= -1

3.使用timeit包:

from timeit import timeit,Timer
timeit('sqrt(2)','from math import sqrt',number=100000000)

4.使用 cProfile 进行性能测试

import cProfile
from functools import lru_cache
@lru_cache(maxseze=None)
def fib(n):
    if n == 0 :
        return 0 
    if n == 1:
        return 1
    return fib(n-1) + fib(n-2)
print(cProfile.run('fib(1000)'))

你可能感兴趣的:(Python)