在python中使用带有len函数的timeit函数

时间:2015-03-15 19:05:12

标签: python python-3.x

我试图计算程序的运行时间。如何在此代码中使用带有len函数的timeit函数。

代码:

import timeit
def shellSort(alist):
    sublistcount = len(alist)//2
    while sublistcount > 0:

      for startposition in range(sublistcount):
        gapInsertionSort(alist,startposition,sublistcount)

      print("After increments of size",sublistcount,"The list is",alist)


      sublistcount = sublistcount // 2

def gapInsertionSort(alist,start,gap):
    for i in range(start+gap,len(alist),gap):

        currentvalue = alist[i]
        position = i

        while position>=gap and alist[position-gap]>currentvalue:
            alist[position]=alist[position-gap]
            position = position-gap

        alist[position]=currentvalue
    return alist
alist = [54,26,93,17,77,31,44,55,20]
shellSort(alist)
print(alist)
print(timeit.timeit("[len(alist)]","from__main__import shellSort"))

程序给出的错误:

After increments of size 4 The list is [20, 26, 44, 17, 54, 31, 93, 55, 77]

After increments of size 2 The list is [20, 17, 44, 26, 54, 31, 77, 55, 93]

After increments of size 1 The list is [17, 20, 26, 31, 44, 54, 55, 77, 93]

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Traceback (most recent call last):

  File "C:/Users/Mervee/Desktop/shell sort.py", line 29, in <module>

    print(timeit.timeit("[len(alist)]","from__main__import shellSort"))

  File "C:\Python34\lib\timeit.py", line 213, in timeit

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

  File "C:\Python34\lib\timeit.py", line 122, in __init__

    code = compile(src, dummy_src_name, "exec")

  File "<timeit-src>", line 3

    from__main__import shellSort

                               ^
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:0)

你只是在python行中有一个语法错误抱怨;它总是

from module import things

请注意空格很重要。

答案 1 :(得分:0)

  

要让timeit模块访问您定义的函数,您可以传递包含import语句的setup参数:

示例:

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"))

在您的情况下,您需要传递函数的名称来计算程序的运行时间:

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("shellSort()", setup="from__main__import shellSort"))