Python timeit在函数

时间:2017-02-08 07:24:09

标签: python time

因此,我正在尝试使用Python中的timeit / Timer函数来计算强力算法和更高效的nlogn版本之间的差异。我的问题在于时间函数。

from timeit import Timer
import timeit
def BruteForce(A, u):
       for z in A:
            if u-z in A:
                return u, z
        return False

def BinarySearchAlgo(A, u):
    A.sort()
    for z in A:
        if BinarySearch(A, u-z) is True:
            return u, z
    return False

def BinarySearch(list, item):
    if len(list)==0:
        return False
    else:
        midpoint = len(list)//2
        if list[midpoint] == item:
            return True
        elif item < list[midpoint]:
            return BinarySearch(list[:midpoint], item)
        else:
            return BinarySearch(list[midpoint+1:], item)

def tests():
    TestFiles = ['listNumbers-10.txt', 'listNumbers2-10.txt','listNumbers-  100.txt','listNumbers2-100.txt','listNumbers-1000.txt','listNumbers2-   1000.txt','listNumbers-10000.txt','listNumbers2-10000.txt','listNumbers-    100000.txt','listNumbers2-100000.txt','listNumbers-1000000.txt','listNumbers2-  1000000.txt']
    for File in TestFiles:
        results = []
        print("The following are timing tests for the file: ", File)
        with open(File) as inputfile:
            for line in inputfile:
                results.append(int(line.strip()))
        TestNumbers =   [len(results)%2,len(results)%5,len(results)%13,len(results)%99, len(results)%209, len(results)%317, len(results)%464, len(results)%892, len(results)%777]
        for n in TestNumbers:
            BruteForceTime = Timer("BruteForce(results, n)", "from __main__ import BruteForce").timeit()
            BinarySearchTime = Timer("BinarySearchAlgo(results, n)", "from __main__ import BinarySearchAlgo").timeit()

            print("Test Number = ", n, "Brute Force Algo time = ", BruteForceTime, "Binary Search Algo time = ", BinarySearchTime)

在以下两行中,每当我调用tests()函数时,我都会得到结果的错误,并且没有定义n。我的问题是如何将它们导入Timer参数,以便定义它们。

BruteForceTime = Timer("BruteForce(results, n)", "from __main__ import BruteForce").timeit()
BinarySearchTime = Timer("BinarySearchAlgo(results, n)", "from __main__ import BinarySearchAlgo").timeit()

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使用值而不是表达式中的变量:

Timer("BruteForce({}, {})".format(results, n),
      "from __main__ import BruteForce").timeit()