time.time() 返回自 Unix 紀元 (1970-01-01 00:00:00 UTC) 以來的浮點秒數,是測量程式執行時間、生成唯一標識、時間同步的基礎工具。本文深入解析其精度特性、單調性陷阱、高精度替代方案與實戰模式。
import time
ts = time.time()
print(f"時間戳: {ts}") # 1705312800.123456
print(f"本地時間: {time.ctime(ts)}") # Mon Jan 15 14:30:00 2024
print(f"結構化: {time.localtime(ts)}")
| 平台 | 典型精度 | 來源 |
|---|---|---|
| Linux (現代) | 1 微秒 (μs) | clock_gettime(CLOCK_REALTIME) |
| Windows (舊版) | 1~15 毫秒 | GetSystemTimeAsFileTime |
| Windows 10+ | 100 納秒 | GetSystemTimePreciseAsFileTime |
| macOS | 1 微秒 | gettimeofday / mach_absolute_time |
注意: 返回值為 float 並不保證微秒精度,僅表示「盡力提供」。
end - start 可能為負數,導致邏輯錯誤。
import time
# 1. time.perf_counter() - 最高精度,包含睡眠時間 (推薦基準測試)
start = time.perf_counter()
time.sleep(0.1)
elapsed = time.perf_counter() - start # 約 0.1000xxx 秒
# 2. time.monotonic() - 保證單調,不受系統時間調整影響 (推薦超時/間隔)
start = time.monotonic()
# ... 執行任務 ...
if time.monotonic() - start > 30:
print("超時")
# 3. time.process_time() - 僅計算 CPU 時間 (排除睡眠)
start = time.process_time()
# ... 計算密集任務 ...
cpu_used = time.process_time() - start
| 需求 | 推薦函數 | 理由 |
|---|---|---|
| 當前壁鐘時間/時間戳 | time.time() | 標準 Unix 時間,適合日誌、快照、跨系統同步 |
| 測量代碼執行耗時 | time.perf_counter() | 最高精度、含睡眠、跨平台一致 |
| 實現超時/間隔邏輯 | time.monotonic() | 絕不倒退、免受 NTP/用戶調整影響 |
| 分析 CPU 佔用 | time.process_time() | 僅計入 CPU 執行時間 |
| 高精度壁鐘時間 (Python 3.7+) | time.time_ns() | 返回納秒整數,避免浮點精度損失 |
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} 耗時: {elapsed:.6f} 秒")
return result
return wrapper
@timer
def heavy_computation():
sum(i*i for i in range(10**7))
from contextlib import contextmanager
@contextmanager
def measure(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.6f}s")
with measure("資料庫查詢"):
db.query("SELECT * FROM large_table")
import time, uuid
def gen_id():
return f"{int(time.time()*1e6):016x}-{uuid.uuid4().hex[:8]}"
print(gen_id()) # 24b8f3a5c1d2e3f4-a1b2c3d4
time.time() = 壁鐘時間戳,用於「何時發生」time.perf_counter() = 高精度碼表,用於「持續多久」time.monotonic() = 單調碼表,用於「是否超時」time.time() 計算超時或測量短耗時正確選擇時間函數,是寫出可靠、高效能 Python 程式的基礎功力之一。