为什么运行时和timeit在我的python代码中有所不同?

时间:2017-12-03 00:17:06

标签: python performance

我写了下面的代码,试着看看我的功能有多快。我用了timeit。 阶乘结果打印速度非常快(不到1秒),但计时器(func_to_measure())显示为3.3秒。

请帮助我理解为什么这些完全不同。我认为print(factorial(N))Func_to_measure()的运行时间完全相同。

import sys
from timeit import default_timer as timer
sys.setrecursionlimit(10**6)

print("Please enter the number for factorial:")
n=input()
N=int(n)

def factorial(N):
    #print("factorial has been called with n ="+ str(N))
    if(N==0):
        return(1)
    else:
        res=N*factorial(N-1)
        #print("intermediate result for ",N,"* factorial(",N-1,"):",res)
        return res

print(factorial(N)) # it will print very fast(less than 1 second)

def func_to_measure():
    result=factorial(N)

print("starting timer")
start=timer()
for i in range(100000):
    func_to_measure()
end=timer()
elapsed=end-start

print("elapsed time:",elapsed,"secs") # show after 3 seconds

0 个答案:

没有答案