Python: Timing, Benchmark
Timing, Compare Speed
to time a function or compare the speed of different ways to code the same thing, use the builtin lib timeit
.
import timeit
there are several ways to call it:
timeit.timeit(codeString, number=int)
timeit.timeit(functionName, number=int)
timeit.timeit(lambda:functionName(args), number=int)
Example: Time a Code by String
# python 3 import timeit tt = timeit.timeit("""map(lambda x: x+1, range(10))""", number=100) print(tt) # 2.639999999999934e-05
Example: Time a Function with No Argument
# python 3 import timeit # compute needed setup or input before timing xinput = range(10) def f1(): """add 1 to global xinput""" return map(lambda x: x + 1, xinput) tt = timeit.timeit(f1, number=100) print(tt) # 2.0499999999999685e-05
Example: Time a Function with Argument
# python 3 import timeit # timing a function with args def f2(xlist): """add 1 to all element""" return map(lambda x: x + 1, xlist) # compute needed setup or input before timing xinput = range(10) # testing a function with arg tt = timeit.timeit(lambda: f2(xinput), number=100) print(tt) # 2.570000000000003e-05