python performance measure 01

01.性能验证

方法01:

##最基础计时方式来验证性能

exec_times = 100000
orignal_str = "{:<20}{:10.6} s"

def slowest_replace():
    replace_list = []
    for i, char in enumerate(orignal_str):
        c = char if char != " " else "-"
        replace_list.append(c)
    return "".join(replace_list)
 
def slow_replace():
    replace_str = ""
    for i, char in enumerate(orignal_str):
        c = char if char != " " else "-"
        replace_str += c
    return replace_str
 
def fast_replace():
    return "-".join(orignal_str.split())
 
def fastest_replace():
    return orignal_str.replace(" ", "-")

def _time_analyze_(func):
    from time import clock
    start = clock()
    for i in range(exec_times):
        func()
    finish = clock()
    print "{:<20}{:10.6} s".format(func.__name__ + ":", finish - start)

if __name__ == "__main__":
    fun = [slowest_replace,slow_replace,fast_replace,fastest_replace]
    for f in fun:
        _time_analyze_(f)

方法02:

##通过定义类的 __enter__ 和 __exit__ 方法来实现对管理的函数计时

import time

class Timer(object):
    def __init__(self, verbose=False):
        self.verbose = verbose

    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        self.secs = self.end - self.start
        self.msecs = self.secs * 1000    
        if self.verbose:
            print 'elapsed time: %f ms' % self.msecs


fun = [slowest_replace,slow_replace,fast_replace,fastest_replace]
for f in fun:
    with Timer() as t:
        _time_analyze_(f)
    print "=> foo() spends %s s" % t.secs


openstack0-controller0:~/yaowl/_profile # python demo.py
slowest_replace:          0.66 s
=> foo() spends 0.66304397583 s
slow_replace:             0.51 s
=> foo() spends 0.507592916489 s
fast_replace:             0.07 s
=> foo() spends 0.0681991577148 s
fastest_replace:          0.05 s
=> foo() spends 0.0552458763123 s

方法03:

通过装饰器的方式

import time
from functools import wraps

def timer(function):
    @wraps(function)
    def function_timer(*args, **kwargs):
        t0 = time.time()
        result = function(*args, **kwargs)
        t1 = time.time()
        print ("Total time running %s: %s seconds" %
                (function.func_name, str(t1-t0))
                )
        return result
    return function_timer
@timer
def _time_analyze_(func):
    from time import clock
    start = clock()
    for i in range(exec_times):
        func()
    finish = clock()
    #print "{:<20}{:10.6} s".format(func.__name__ + ":", finish - start)

if __name__ == "__main__":
    fun = [slowest_replace,slow_replace,fast_replace,fastest_replace]
    for f in fun:
        _time_analyze_(f)

controller0:~/yaowl/_profile # python demo.py
Total time running _time_analyze_: 0.684864997864 seconds
Total time running _time_analyze_: 0.482245922089 seconds
Total time running _time_analyze_: 0.0729959011078 seconds
Total time running _time_analyze_: 0.0589439868927 seconds

方法04:

##通过python自带库timeit 详细参照 https://docs.python.org/2/library/timeit.html

$ python -m timeit '"-".join(str(n) for n in range(100))'
10000 loops, best of 3: 40.3 usec per loop
$ python -m timeit '"-".join([str(n) for n in range(100)])'
10000 loops, best of 3: 33.4 usec per loop
$ python -m timeit '"-".join(map(str, range(100)))'
10000 loops, best of 3: 25.2 usec per loop

$ python -m timeit 'try:' '  str.__nonzero__' 'except AttributeError:' '  pass'
100000 loops, best of 3: 15.7 usec per loop
$ python -m timeit 'if hasattr(str, "__nonzero__"): pass'
100000 loops, best of 3: 4.26 usec per loop

$ python -m timeit 'try:' '  int.__nonzero__' 'except AttributeError:' '  pass'
1000000 loops, best of 3: 1.43 usec per loop
$ python -m timeit 'if hasattr(int, "__nonzero__"): pass'
100000 loops, best of 3: 2.23 usec per loop

 

posted on 2017-09-18 17:43  yaoweilei  阅读(285)  评论(0编辑  收藏  举报

导航