萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python time.time() 獲取當前時間戳完全指南:精度、單調性、實戰用法

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
macOS1 微秒gettimeofday / mach_absolute_time

注意: 返回值為 float 並不保證微秒精度,僅表示「盡力提供」。

單調性陷阱 (關鍵)

time.time() 不保證單調遞增!
  • NTP 時間同步可能向前/向後調整系統時鐘
  • 用戶手動修改系統時間
  • 虛擬機暫停/恢復導致時間跳躍
  • 閏秒插入
後果: 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")

生成唯一 ID (含時間戳)


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 程式的基礎功力之一。

copyright © 萬盛學電腦網 all rights reserved