Python 自帶計時工具 timeit

碼廄技術博客

Python 自帶計時工具 timeitpython

 

Timer 類:linux

__init__(stmt="pass", setup="pass", timer=default_timer)app

    stmt 是執行語句,setup 是導入執行語句環境dom

print_exc(file=None)函數

timeit(number=default_number)工具

    返回測試所用秒數,number 是每一個測試中調用被計時語句的次數測試

repeat(repeat=default_repeat, number=default_number).net

    返回測試所用秒數列表,repeat 是重複整個測試的次數,number 是每一個測試中執行語句的次數code

快捷方法:get

timeit(stmt="pass", setup="pass", timer=default_timer, number=default_number)

    = Timer(stmt, setup, timer).timeit(number)

repeat(stmt="pass", setup="pass", timer=default_timer, repeat=default_repeat, number=default_number)

    = Timer(stmt, setup, timer).repeat(repeat, number)

 

default_timer 在 win32 下是 time.clock(),在 linux 下是 time.time()

default_number = 1000000

default_repeat = 3

 

實例:

import timeit

def func1(x):
    pow(x, 2)

def func2(x):
    return x * x

v = 10000

func1_test = 'func1(' + str(v) + ')'
func2_test = 'func2(' + str(v) + ')'

print timeit.timeit(func1_test, 'from __main__ import func1')
print timeit.timeit(func2_test, 'from __main__ import func2')

print timeit.repeat(func1_test, 'from __main__ import func1')
print timeit.repeat(func2_test, 'from __main__ import func2')

 

 

實例2:

#! /usr/bin/env python
# -*- coding: u8 -*-
import random
import timeit

def randDiff( k,n ):
    '產生k個不相等的從1到n的隨機數'
    p = []
    y1 = [random.randrange(1,n+1) for i in range(n)]
    y2 = []
    y2.extend(y1)
    y1.sort()
    for j in range(k):
        temp1 = y1[j]
        temp2 = y2.index(temp1)
        p.append(temp2 + 1)
        y2[temp2] = -1
    return p

def randDif(k,n):
    '新函數,生成k個1到n之間不相等的隨機數'
    if k>n:
        return []
    a = range(1,n+1)
    random.shuffle(a)
    return a[:k]

# 關於上面兩個函數:http://www.oschina.net/question/153568_23095?sort=time

if __name__=='__main__':
    print timeit.repeat("randDiff(3, 10)", "from __main__ import randDiff", timeit.default_timer, 3, 10000)
    print timeit.repeat("randDif(3, 10)", "from __main__ import randDif", timeit.default_timer, 3, 10000)

相關文章
相關標籤/搜索