計算運行時間工具timeit

timeit的功能和用法

timeit 模塊提供了測試一小段代碼運行時間的功能。我前面有一篇文章用它來測試定義 __slots__ 對對象訪問速度的提升情況,參見這裏
官方文檔 上有下面這樣的使用例子:

# 從命令行調用
python -m timeit '"-".join([str(n) for n in range(100)])'

# 從REPL調用
>>> import timeit
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.7288308143615723

使用 timeit 的時候可以直接調用其定義好的 timeit.timeit , timeit.repeat , timeit.default_timer 方法,或者定義一個類 timeit.Timer ,使用本身的方法。

# API

timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)

timeit.repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)

class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)¶
  • timeit() 接受的第一個參數stmt爲要計算時間的表達式,第二個參數setup爲初始化的表達式。
  • timer參數爲計時器,在不同平臺默認不一樣,參照這裏 ,但不管是Unix還是Windows測得的時間都是系統經過的時間,所以是有可能被正在運行的其它程序影響的。
  • number參數是表達式執行的次數,所以這裏返回的時間是執行1000000次總和的時間。
  • timeit.repeat() 中的repeat參數是測試重複執行的次數,相當於調用number次的timeit(),number默認爲3,返回3次運行時間的列表,通常可以取min()來評估程序的執行時間。
  • timeit.repeat() 中除了最小值其他的值得參考意義可能不大,因爲有可能是受到系統中其它程序影響導致的
  • 注意python版本不同導致的接口參數不同,這裏默認採用python2.7版本

接下來看一些複雜點的示例

# 多行表達式的調用
>>> import timeit
>>> attribute is missing
>>> s = """\
... try:
...     str.__nonzero__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.9138244460009446


# 測試函數調用時間
def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

其它

當我在網上瀏覽timeit相關資源時看到了這篇文章, 上面提到了通過上下文管理器(context manager)實現一個計時器,利用了變量的生命週期相關特性(#TODO),雖然就像作者所說,可以加上其它的特性比如循環次數等以及更優雅的實現一個計時器,代碼如下,可供參考:

# Source code: https://gist.github.com/pengmeng/78a25663c20ab8890b81
__author__ = 'mengpeng'
import time


class timeme(object):
    __unitfactor = {'s': 1,
                    'ms': 1000,
                    'us': 1000000}

    def __init__(self, unit='s', precision=4):
        self.start = None
        self.end = None
        self.total = 0
        self.unit = unit
        self.precision = precision

    def __enter__(self):
        if self.unit not in timeme.__unitfactor:
            raise KeyError('Unsupported time unit.')
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        self.total = (self.end - self.start) * timeme.__unitfactor[self.unit]
        self.total = round(self.total, self.precision)

    def __str__(self):
        return 'Running time is {0}{1}'.format(self.total, self.unit)

運行示例:

from timeme import timeme
with timeme('ms', 6) as t:
    result = sum(range(100000))

print(t) # Running time is 5.2948ms
print(t.total) # 5.2948

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章