Sobes.tech
Junior — Middle

What are the differences between the functions time.time() and time.monotonic() in Python, and what are their features?

sobes.tech AI

Answer from AI

The time.time() function returns the current time in seconds since the epoch (usually January 1, 1970 UTC). This system time can change, for example, when manually adjusting the clock or synchronizing with a time server.

The time.monotonic() function returns a monotonically increasing time, which never decreases and is unaffected by system time changes. It is useful for measuring time intervals, such as timers or performance measurements, as it guarantees the correctness of the difference between two calls.

Example of using time.monotonic() for measuring execution time:

import time
start = time.monotonic()
# code to measure
end = time.monotonic()
print(f"Execution time: {end - start} seconds")

Thus, time.time() is suitable for getting the current date and time, while time.monotonic() is for reliable interval measurement.