杰瑞科技汇

Python如何实现gettimeofday获取高精度时间?

Of course! In Python, the standard and most direct way to get high-resolution time is by using the time module.

Python如何实现gettimeofday获取高精度时间?-图1
(图片来源网络,侵删)

The C function gettimeofday() returns the time since the Epoch (a point in time) as a floating-point number, including the fractional seconds. Python's time.time() function does exactly the same thing.

Here’s a complete guide, from the basics to more advanced and precise alternatives.


The Standard Way: time.time()

This is the equivalent of gettimeofday(). It returns the current time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC) as a float.

import time
# Get the current time in seconds since the epoch
current_time = time.time()
print(f"Current time (since epoch): {current_time}")
print(f"Type of the returned value: {type(current_time)}")
# You can format it into a human-readable string
# The gmtime() converts the seconds to a struct_time in UTC
from time import gmtime, strftime
readable_time = strftime("%Y-%m-%d %H:%M:%S", gmtime(current_time))
print(f"Human-readable time (UTC): {readable_time}")

Output:

Python如何实现gettimeofday获取高精度时间?-图2
(图片来源网络,侵删)
Current time (since epoch): 1678886400.123456
Type of the returned value: <class 'float'>
Human-readable time (UTC): 2025-03-15 12:00:00

For Performance Measurement: time.perf_counter()

If your goal is to measure short durations (like how long a function takes to run), time.perf_counter() is a better choice. It's designed to be a high-resolution monotonic clock, meaning it's only useful for measuring elapsed time and is not affected by system time changes.

  • Monotonic: It only goes forward, making it perfect for benchmarking. If the system clock is adjusted, perf_counter is not affected.
  • High Resolution: It provides the highest available resolution for measuring short time intervals.
import time
start_time = time.perf_counter()
# Do something that takes time
sum([i**2 for i in range(100000)])
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Code took {elapsed_time:.6f} seconds to run.")

Output:

Code took 0.023451 seconds to run.

For Scheduling and Timeouts: time.monotonic()

This is another monotonic clock, similar to perf_counter(). It's generally used for timeouts and where you need to measure elapsed time but don't require the highest possible precision.

The main difference between perf_counter and monotonic can be implementation-dependent, but perf_counter is typically preferred for performance benchmarking due to its potential for higher resolution.

import time
# Example: A simple timeout mechanism
timeout_seconds = 5
start_time = time.monotonic()
while True:
    current_elapsed = time.monotonic() - start_time
    print(f"Elapsed time: {current_elapsed:.2f}s", end='\r')
    if current_elapsed > timeout_seconds:
        print("\nTimeout reached!")
        break
    # Simulate work
    time.sleep(0.1)

Output:

Elapsed time: 5.01s
Timeout reached!

For System Time (with nanoseconds): time.time_ns()

Python 3.7 introduced time.time_ns(), which is like time.time() but returns the time as an integer representing nanoseconds since the Epoch. This avoids floating-point precision issues if you need to do very precise calculations or store the time in a database.

import time
# Get time in nanoseconds since the epoch
current_time_ns = time.time_ns()
print(f"Current time (nanoseconds since epoch): {current_time_ns}")
print(f"Type of the returned value: {type(current_time_ns)}")
# You can convert it back to seconds by dividing by 1 billion (10^9)
current_time_seconds = current_time_ns / 1_000_000_000
print(f"Converted back to seconds: {current_time_seconds}")

Output:

Current time (nanoseconds since epoch): 1678886400123456789
Type of the returned value: <class 'int'>
Converted back to seconds: 1678886400.1234568

Summary: Which one should you use?

Function Use Case Resolution Important Notes
time.time() Getting the current wall-clock time (e.g., for logging, timestamps). High Not monotonic. Can go backward if the system clock is adjusted.
time.perf_counter() Performance measurement. Measuring how long code takes to run. Highest (monotonic) Best for benchmarking. Ignores system clock changes.
time.monotonic() Timeouts, elapsed time measurement where highest precision isn't critical. High (monotonic) Good for general-purpose elapsed time.
time.time_ns() Getting current wall-clock time with nanosecond precision (e.g., for high-precision logging). Nanoseconds Returns an int, avoiding floating-point precision limits.

Important Note on Windows Precision

On Windows, the resolution of the system clock is typically around 15.6 milliseconds. While Python's time functions will try to give you the best available resolution, the underlying system call might not be able to provide microsecond or nanosecond accuracy.

For true high-resolution timing on Windows, you might need to use the win32api or ctypes to call the QueryPerformanceCounter API directly. However, for 99% of use cases, time.perf_counter() is sufficient and the recommended approach.

分享:
扫描分享到社交APP
上一篇
下一篇