[Tutor] time vs. timeit
Steven D'Aprano
steve at pearwood.info
Tue Aug 26 13:31:10 CEST 2014
On Tue, Aug 26, 2014 at 09:56:55AM +0530, diliup gabadamudalige wrote:
> Hi all,
>
> 1. why do some say that the time module is more accurate than the timeit
> module?
> s = time.time()
> or
> s = timeit.timeit()
You will have to ask them.
Since the two functions do very different things, I don't understand how
they are comparing them. That's a bit like saying that len() is more
accurate than math.sin().
> 2. Why is it that both modules never return the same answer on each run?
time.time() returns the current time, in seconds since the start of the
Unix Epoch. At midnight, 1st January 1970 UTC, time.time() would have
returned 0. One second later, it would return 1. At 3:15:20am Friday
2nd January 1970, it would return 98120.
I can check my calculation:
py> import time
py> time.ctime(98120)
'Fri Jan 2 13:15:20 1970'
My local timezone is 10 hours ahead of UTC, so that is correct.
time.time() will not return the same value because time keeps moving
forward. The only way to get it to return the same value would be to
set the computer's clock backwards.
timeit.timeit is not like time(). It doesn't return an absolute time,
but a *difference* between two times. It measures how long it takes to
run some code. For example, on my computer:
py> timeit.timeit("x = len([])")
0.1940888217650354
getting the length of the empty list [] one million times takes 0.19
seconds, or about 0.19μs each. On your computer, it may be faster, or
slower. If I do it again:
py> timeit.timeit("x = len([])")
0.19202891178429127
I get *about* the same value, but not exactly. It's not exactly the same
speed because my computer is not doing exactly the same thing each time.
There are other processes running: background tasks, virus checkers,
internet downloads, the operating system is busy doing whatever it is
that the operating system does. If I look on my computer, right now,
there are at least 260 processes running:
[steve at ando ~]$ ps aux | wc -l
260
The amount of time that timeit() reports will depend very slightly on
how busy the computer is doing other things. You know that for yourself:
if the computer is overloaded, doing too much, everything slows down.
--
Steven
More information about the Tutor
mailing list