Python之统计程序运行耗时

思路:程序开始前后各记录一个时间点,两个时间点相减即程序运行耗时时间

方法1:普通计算方法

import time
import sys
import os

start_time = time.clock()
time.sleep(5)
stop_time = time.clock()
cost = stop_time - start_time
print("%s cost %s second" % (os.path.basename(sys.argv[0]), cost))

# 结果
1.py cost 4.99955353477297 second

方法2:利用装饰器

import time


def time_me(fn):
    def _wrapper(*args, **kwargs):
        start = time.clock()
        fn(*args, **kwargs)
        print("%s cost %s second" % (fn.__name__, time.clock() - start))
    return _wrapper


# 这个装饰器可以在方便地统计函数运行的耗时。用来分析脚本的性能是最好不过了
# 这样用调用:
@time_me
def test(x, y):
    time.sleep(0.1)
    return x + y


@time_me
def test2(x):
    time.sleep(0.2)
    return x

test(1, 2)
test2(2)

# 输出:
# test cost 0.1001529524 second
# test2 cost 0.199968431742 second

方法3:

import time
import functools


def time_me(info="used"):
    def _time_me(fn):
        @functools.wraps(fn)
        def _wrapper(*args, **kwargs):
            start = time.clock()
            fn(*args, **kwargs)
            print("%s %s %s"%(fn.__name__, info, time.clock() - start), "second")
        return _wrapper
    return _time_me


@time_me()
def test(x, y):
    time.sleep(0.1)
    return x + y


@time_me("cost")
def test2(x):
    time.sleep(0.2)
    return x

test(1, 2)
test2(2)

# 结果
# test used 0.09979820245441397 second
# test2 cost 0.1999990525936827 second

 

posted @ 2016-07-20 22:18  每天进步一点点!!!  阅读(6764)  评论(0编辑  收藏  举报