Python 3.3中的执行时间

时间:2015-06-21 13:24:38

标签: performance python-3.x

我读了这个topic,因为我忘了我几个月前在网上找到的方法,我不知道为什么今天我找不到它,它很简单,效果很好但是...... 。

所以我尝试了一种方法,但我觉得它不好用,或者我5岁的电脑比今天的电脑好......

import time

debut=time.clock()

def t(n): 
    aaa=[]
    b=n-1
    c=0
    if n==0 or n==1:
        return 1
    else:
        while n != 1: 
            if n % 2==0: 
                n=n//2
                aaa.append(n)
            else: 
                n = n+b
                aaa.append(n)
    return [b,b+1]+aaa, len(aaa)+2

fin=time.clock()

print(t(100000),fin-debut)

对于n = 10.000.000我可以在我的头脑中计算大约5个secondes并且计算机总是返回3.956927685067058e-06 ...有人可以解释一下吗?

我找到的方法使用了这个from time import perf_counter as pc

我必须返回print(pc()-t)

如果有人可以启发我,因为我真的不记得这个方法。

提前谢谢

2 个答案:

答案 0 :(得分:2)

查看timeit模块https://docs.python.org/3.0/library/timeit.html

你会为你设置类似......

time = Timer( "t(100000)", "from __main__ import t")
print("time: ", timer.timeit(number=1000))

答案 1 :(得分:0)

您正在测量定义功能所需的时间。 这将测量函数的执行:

import time

def t(n): 
    aaa=[]
    b=n-1
    c=0
    if n==0 or n==1:
        return 1
    else:
        while n != 1: 
            if n % 2==0: 
                n=n//2
                aaa.append(n)
            else: 
                n = n+b
                aaa.append(n)
    return [b,b+1]+aaa, len(aaa)+2

start = time.time()
value = t(100000)
end = time.time()

duration = end - start
print(value, duration)