3

Why does time.clock() give the wrong result? The code is as follows:

time_start1 = time.time()
time.sleep(5)
bb = time.time() - time_start1;
print bb;
time_1 = time.clock()
time.sleep(5)
cc = time.clock() - time_1
print cc

The results are:

5.00506210327
0.006593

The second one should be 5.0, but why is it 0.006? My OS is Ubuntu 14.04LTS 64-bit. My version of IDLE is 2.7.6.

Thanks!

Fengyang Wang
  • 11,901
  • 2
  • 38
  • 67
tqjustc
  • 3,624
  • 6
  • 27
  • 42

3 Answers3

14

time.time() and time.clock() are measuring different things.

time.time() measures wall clock elapsed time, since the Unix epoch.

On a Linux system, time.clock() is measuring processor time, which isn't the elapsed time in seconds.

Processor time is an approximation of how much time was spent by the processor executing that code, as defined in the man pages for clock (which is the underlying call to the operating system that time.clock() makes on a Linux system).

Python source: https://docs.python.org/2/library/time.html

Clock source: http://linux.die.net/man/3/clock

Leigh
  • 12,038
  • 4
  • 28
  • 36
4

On Linux systems, time.clock() returns the processor time, not the time you expect.

time.time() measures wall clock elapsed time since the epoch, while on Linux systems, time.clock() measures the processor time.

>>> x = time.clock()
>>> time.sleep(1)
>>> print time.clock()-x
0.001644
>>> 

From the sources:

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

Python 3 Update: time.clock() was removed in Python 3.3, consider using time.perf_counter() instead.

  • time.time() is measuring elapsed time since the Unix epoch (a reference point in 1970).

  • time.clock() is measuring processor time, which isn't a date or time in seconds.

  • time.perf_counter() is measuring time passing by with the highest precision available on the current platform.

Processor clock time is an approximation of how much time is spent in the CPU to execute instructions. Historically, a processor running at 3 GHz would have 3 billion ticks per second, but modern processors don't operate exactly like that anymore.

Clock time is used for benchmarking where extreme precision is required (in the order of nanoseconds). Most time functions are meant for human time/date and may only be accurate to a millisecond or so. Vary with the OS and platform.

Python 3.3 redid time functions. It added some easy-to-use functions that work across platforms (time.perf_counter) and it exposed some platform-specific functions for advanced use cases.

https://docs.python.org/3/library/time.html

user5994461
  • 5,301
  • 1
  • 36
  • 57