Python 3 – time clock() Method
The time
module in Python provides various functions related to time. One such function is clock()
, which is used to get the current processor time as a floating-point number expressed in seconds. This function is useful for benchmarking code and for timing how long a particular operation takes.
Syntax
time.clock()
Parameters
This function does not take any parameters.
Return Value
The clock()
function returns the current processor time as a floating-point number expressed in seconds.
Example
import time
start_time = time.clock()
for i in range(1000000):
j = i**2
end_time = time.clock()
print("Time taken:", end_time - start_time, "seconds")
Output: Time taken: 0.15043828958539956 seconds
In the above example, we have imported the time
module and used the clock()
function to get the processor time before and after a loop that calculates squares. We then subtracted the start time from the end time to get the total time taken by the loop and printed it to the console.
It’s important to note that the clock()
function only returns the processor time and not the actual time elapsed. This means that if the system is running other processes or running on multiple CPUs, the returned time may not accurately reflect the actual elapsed time.
In addition, the clock()
function has been deprecated since Python 3.3 and replaced with the perf_counter()
and process_time()
functions. These functions have improved precision and are better suited for measuring elapsed time in real-world scenarios.
Example using perf_counter()
import time
start_time = time.perf_counter()
for i in range(1000000):
j = i**2
end_time = time.perf_counter()
print("Time taken:", end_time - start_time, "seconds")
Output: Time taken: 0.11203236588007303 seconds
In the above example, we have used the perf_counter()
function instead of the clock()
function. This results in a more accurate measurement of elapsed time.
Conclusion
The clock()
function in Python’s time
module is used to get the current processor time as a floating-point number expressed in seconds. This function is useful for benchmarking code and measuring how long an operation takes. However, since it has been deprecated since Python 3.3, it is recommended to use the perf_counter()
and process_time()
functions for measuring elapsed time in real-world scenarios.