定时功能时如何使用timeit [英] How to use timeit when timing a function
问题描述
首先让我说我对python几乎一无所知,但是必须用三种不同的语言(已经用Java和c ++完成)编写程序.
Let me start off by saying I know almost nothing about python but have to write a program in three different languages (already done in java and c++).
我需要能够对方法的执行进行一定次数的计时,然后打印整个执行时间所花费的时间.
I need to be able to time the execution of a method a certain number of times and then print the time it took for the over-all execution time.
即
我有函数A
(这是performSearch(arrayTest)
,其中arrayTest
是已知大小的数组). A
被执行10次
I have function A
(which is performSearch(arrayTest)
where arrayTest
is an array of known size). A
is executed 10 times
我需要确定从执行A
到执行A
之后所花费的时间.
I need to be able to time how long it took from before A
was executed to after A
was executed.
推荐答案
You can read how to use timeit here.
并假设您在同一个文件中有一个名为performSearch的函数,那么下面的运行timeit将起作用.
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)
哪个返回:
0.000162031766607
这篇关于定时功能时如何使用timeit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!