How to use timeit when timing a function

前端 未结 5 1798
南旧
南旧 2020-12-16 16:41

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 a

5条回答
  •  悲哀的现实
    2020-12-16 17:36

    You can use below code as an example:

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

    The results are :

    0.00784516334534
    [0.0009770393371582031, 0.00036597251892089844, 0.00037407875061035156]
    0.414484977722
    

    The unit for the results is second. More examples are exist in python website. enter link description here

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

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

    The result is :

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

    As you can see, the unit is macro second.

提交回复
热议问题