【问题标题】:Using timeit module in Python with function在 Python 中使用带有函数的 timeit 模块
【发布时间】:2014-12-22 16:05:41
【问题描述】:

我在 Python 中创建了一个脚本来计算素数序列的 X 个指定数字,这本身就可以正常工作。

但是,我正在寻找此脚本在终端中运行需要多长时间,并且我从 Internet 了解到 timeit 模块是执行此操作的最佳方式。

但是,Python 网站上的描述和其他与此相关的问题与我的情况完全无关。这是代码。

P = 2
Y = 1

def Main(P, Y):
    X = int(raw_input('choose number: '))
    while Y <= X:
        isprime = True
        for x in range(2, P - 1):
            if P % x == 0:
                isprime = False
        if isprime:
            print P
            Y += 1
        P += 1

Main(P, Y)

基本上,在这种情况下我将如何使用 timeit 模块,以便它打印出序列中的数字(如上面的代码允许的那样),然后打印出计算指定数量的时间数字?

是否可以在不对当前代码进行大量编辑的情况下做到这一点?

【问题讨论】:

  • 当前函数无法定时,因为逻辑与用户输入相关,最好将逻辑拆分到另一个函数中。

标签: python terminal timeit


【解决方案1】:

为此使用timeit 将包括算法/函数所花费的时间加上用户传递输入所花费的时间,并且在计算算法/函数的完成时间时包含用户输入时间并不是一个好的做法。

所以最好使用datetime模块并避免用户输入时间为:

from datetime import datetime as dt
P = 2
Y = 1

def Main(P, Y):
    X = int(raw_input('choose number: '))
    t1 = dt.now() # Get function starting time
    # It is better to get starting time after user input because user can take any amount of time to pass the input
    while Y <= X:
        isprime = True
        for x in range(2, P - 1):
            if P % x == 0: 
                isprime = False
        if isprime:
            print P
            Y += 1
        P += 1
    t2 = dt.now() # Get function completion time
    print 'Total time taken = {} seconds'.format((t2-t1).total_seconds()) # Print time difference in seconds

Main(P, Y)

如果你想使用timeit 来做的话。代码如下:

timeit.timeit('Main(P,Y)', 'from __main__ import Main,P,Y', number=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多