How to return the current CPU time in Python?

In this article, we retrieve the current CPU time in Python. We use the time() method which is imported from the python time module.

The time module in Python provides various methods and functions related to time. Here we use the time.time() method to get the current CPU time in seconds. The time is calculated since the epoch. It returns a floating-point number expressed in seconds.

Epoch is the starting point of time and is platform-dependent. The epoch is January 1, 1970, 00:00:00 (UTC) on Windows and most Unix systems, and leap seconds are not included in the time in seconds since the epoch.

We use time.gmtime(0) to get the epoch on a given platform.


The syntax of time() method is as follows.


This method returns a float value that represents the seconds since the epoch.


In the following example we get the current cpu time using the time.time() method from the time module and we also retrieve the epoch of a particular platform(Windows).

import time obj = time.gmtime(0) epoch = time.asctime(obj) print("The epoch is:",epoch) curr_time = time.time() print(curr_time)


Output The output of the above code is as follows;

The epoch is: Thu Jan  1 00:00:00 1970


Note that different systems will have different accuracy based on their internal clock setup (ticks per second). but it's generally at least under 20ms. Also note while this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

Updated on: 02-Nov-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started