14

首先让我说我对 python 几乎一无所知,但必须用三种不同的语言编写程序(已经用 java 和 c++ 完成)。

我需要能够为方法的执行计时一定次数,然后打印整个执行时间所花费的时间。

IE

我有函数A(这是performSearch(arrayTest)一个arrayTest已知大小的数组)。A执行 10 次

我需要能够计算从执行之前A到执行之后需要多长时间A

4

5 回答 5

13

You can read how to use timeit here.

And assuming you have a function called performSearch in the same file that your running timeit from the following would work.

import timeit

def performSearch(array):
    array.sort()


arrayTest = ["X"]*1000

if __name__ == "__main__":
    print timeit.timeit("performSearch(arrayTest)","from __main__ import performSearch, arrayTest",number=10)

Which returns:

0.000162031766607
于 2013-09-25T16:57:44.197 回答
10

你可以这样做:

import time

start = time.time()
A()
end = time.time()
print "Took %f ms" % ((end - start) * 1000.0)
于 2013-09-25T17:00:06.517 回答
2

如果你想要更简单的东西

import time
startMillis = int(round(time.time() * 1000))
print startMillis
time.sleep(5) # this is your function that takes time to execute
endMillis = int(round(time.time() * 1000))
print endMillis

timeTaken = endMillis - startMillis
于 2013-09-25T17:00:36.800 回答
2

您可以使用以下代码作为示例:

import timeit

def string_generator(size):
    return (size/8) * "ABCDEFGH"

if __name__ == "__main__":
    #the below line runs the statement inside of '' for 100 times (number).
    print timeit.timeit('"-".join(str(n) for n in range(100))',number=100)
    #the below line runs the statement inside of '' for 10 times (number) and repeat it 3 times.
    print timeit.repeat('"-".join(str(n) for n in range(100))',repeat=3,number=10)
    #if you would like to time a function, you can do it similar to below example:
    print timeit.timeit("string_generator(2**12)", setup="from __main__ import string_generator")

结果是:

0.00784516334534
[0.0009770393371582031, 0.00036597251892089844, 0.00037407875061035156]
0.414484977722

结果的单位是秒。python网站中存在更多示例。 在此处输入链接描述

你也可以使用 ipython。下面列出了相同的示例。

In [25]: %timeit "-".join(str(n) for n in range(100))

结果是:

10000 loops, best of 3: 22.9 µs per loop

如您所见,单位是宏秒。

于 2014-12-10T00:34:40.287 回答
1

是的,只是时间。

前任

total= 0
for i in range(1000):
    start= time.clock()
    function()
    end= time.clock()
    total += end-start
time= total/1000
于 2013-09-25T17:01:18.590 回答