(Aug-26-2019, 09:03 AM)Malt Wrote: here it is displaying timer after printing okay for 4 times.You don't need loop with timeit is doing loop in
number=4
.It run the code 4 times and give average time back.
Be using
print()
as mention you get different result back.This is not how fast the code run,but the printing to screen in interactive shell in this case.
Here a more realistic example there where a discussion a while back about which was faster,
word[0]
or startswith()
.See that i don't use
print()
here i want to measure code speed,and not the printing to screen.import timeit def time_1(word): if word[0] in ('w','x','y','z'): f'word <{word}> has a first letter in sequence <wxyz>' def time_2(word): if word[0] in 'wxyz': f'word <{word}> has a first letter in sequence <wxyz>' def time_3(word): if word.startswith(('w','x','y','z')): f'word <{word}> has a first letter in sequence <wxyz>' lst = ['time_1', 'time_2', 'time_3'] for test in lst: t = timeit.Timer(f"{test}('war'*5)", f'from __main__ import {test}').timeit(number=10000000) print(f'{test} --> {t:.2f}')So this run each code in function 10000000 times,and we get average time back.
Output:E:\div_code
λ python time_startswith.py
time_1 --> 3.49
time_2 --> 3.53
time_3 --> 5.01
So word[0]
is a little faster than startswith()
.Dos this mean that should use
word[0]
?My answer was no because
startswith()
is more readable and the time differences is really small.