How to use timeout when synchronizing a function

Let me start by saying that I know almost nothing about python, but I need to write a program in three different languages ​​(already in java and C ++).

I need to be able to run the method a certain number of times, and then print the time spent on the entire run time.

those.

I have a function A (which performSearch(arrayTest) , where arrayTest is an array of known size). A runs 10 times

I need to know how much time it took before A was executed after A executed.

+4
source share
5 answers

You can read how to use timeit here .

And suppose you have a function called performSearch in the same file as your working period from the following.

 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) 

What returns:

 0.000162031766607 
+5
source

You can do something like this:

 import time start = time.time() A() end = time.time() print "Took %f ms" % ((end - start) * 1000.0) 
+2
source

if you want something simpler

 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 
0
source

yes well, it's just time.

ex

 total= 0 for i in range(1000): start= time.clock() function() end= time.clock() total += end-start time= total/1000 
0
source

As an example, you can use the code below:

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

Results:

 0.00784516334534 [0.0009770393371582031, 0.00036597251892089844, 0.00037407875061035156] 0.414484977722 

The unit for the results is the second. Additional examples exist on the python website. enter the link here

Also you can use ipython. The same example is given below.

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

Result:

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

As you can see, the block takes the second place.

0
source

All Articles