-2

I have a long list. I need to get the first element in the loop and remove it. So I'm trying to compare two functions that do it, but every time I'm getting different time execution.

from timeit import timeit
>>> def foo(l):
    start = timeit()
    while l:
        l.pop(0)
    end = timeit()
    return end - start

>>> def bar(l):
    start = timeit()
    l.reverse()
    while l:
        l.pop()
    end = timeit()
    return end - start

l = [i for i in range(100000)]
>>> for i in range(10):
    print(bar(v.copy()) - foo(v.copy()))


0.00021689999266527593
-0.015974199995980598
-0.0048112000222317874
0.0016583999822614715
-0.03471089998492971
-0.0077514999866252765
-0.0015070999943418428
0.0010934000019915402
-0.005327999999281019
0.000683299993397668
>>> 

Am I doing everything right?

salius
  • 113
  • 7
  • No, you seem to be confusing `timeit.timeit` with `time.time`. You should read the documentation of both to get an understanding of what they do and how to use them. – mkrieger1 May 02 '20 at 09:57
  • As I get it, the only difference is that eventually "timeit " is more precisely – salius May 02 '20 at 10:00
  • 1
    See also [How to use timeit module](https://stackoverflow.com/questions/8220801/how-to-use-timeit-module). – mkrieger1 May 02 '20 at 10:09

1 Answers1

2

the correct way to use timeit would be:

>>> import timeit
>>> timeit.timeit('import time; time.sleep(1)', number=10 )
10.008471012115479
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43