ZetCode

Python time.time 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨了 Python 的 time.time 函数,该函数返回自 epoch 以来(即 1970 年 1 月 1 日 00:00:00 UTC)的当前时间(以秒为单位)。我们将介绍时间戳生成、性能测量和实际的计时示例。

基本定义

time.time 函数以浮点数形式返回自 epoch 以来(即 1970 年 1 月 1 日 00:00:00 UTC)的当前时间(以秒为单位)。

主要特点:平台相关的精度(通常为微秒)、在大多数系统上是单调递增的,并且可用于计时操作和日志记录。返回值是一个浮点数,以实现亚秒级精度。

基本时间戳生成

time.time 最简单的用法是生成当前时间戳。此示例展示了基本用法以及转换为其他时间格式。

basic_time.py
import time

# Get current timestamp
timestamp = time.time()
print(f"Current timestamp: {timestamp}")

# Convert to readable format
local_time = time.localtime(timestamp)
print(f"Local time: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)}")

# Convert to UTC
utc_time = time.gmtime(timestamp)
print(f"UTC time: {time.strftime('%Y-%m-%d %H:%M:%S', utc_time)}")

此示例演示了如何获取当前时间戳并将其转换为本地和 UTC 时间格式。时间戳是一个具有亚秒级精度的浮点数。

strftime 函数根据指定的格式代码将时间结构体格式化为人类可读的字符串。

测量代码执行时间

time.time 通常用于测量代码执行持续时间。此示例展示了如何以微秒精度对代码块进行计时。

timing.py
import time

def slow_function():
    # Simulate work
    time.sleep(1.5)

# Start timer
start_time = time.time()

# Execute code to time
slow_function()

# Calculate duration
end_time = time.time()
duration = end_time - start_time

print(f"Function took {duration:.4f} seconds")

此模式对于性能测试非常有用。开始时间在执行之前捕获,结束时间在执行之后捕获。两者的差值给出持续时间。

:.4f 格式说明符显示持续时间,精确到小数点后 4 位,以实现毫秒精度。

将 Time.time 与 Time.perf_counter 进行比较

虽然 time.time 测量的是挂钟时间,但 time.perf_counter 为基准测试提供最高的可用分辨率。此示例比较了它们。

comparison.py
import time

def test_function():
    sum(range(1000000))

# Using time.time()
start = time.time()
test_function()
end = time.time()
print(f"time.time(): {end - start:.6f} sec")

# Using time.perf_counter()
start = time.perf_counter()
test_function()
end = time.perf_counter()
print(f"time.perf_counter(): {end - start:.6f} sec")

time.time 受系统时钟更改的影响,而 perf_counter 是单调递增的,更适合短时间间隔。

对于大多数计时需求,首选 perf_counter,而 time 更适合实际时间戳。

创建超时

time.time 可以通过将当前时间与截止时间进行比较来实现超时。此示例展示了一个超时装饰器。

timeout.py
import time

def timeout(seconds):
    def decorator(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            elapsed = time.time() - start
            if elapsed > seconds:
                raise TimeoutError(f"Function exceeded {seconds} second timeout")
            return result
        return wrapper
    return decorator

@timeout(2)
def potentially_slow_operation():
    time.sleep(1.5)  # Simulate work
    return "Success"

print(potentially_slow_operation())  # Success

@timeout(1)
def too_slow_operation():
    time.sleep(1.5)
    return "Should timeout"

try:
    too_slow_operation()
except TimeoutError as e:
    print(f"Caught: {e}")

该装饰器测量执行时间,如果超过限制则引发异常。此模式对于强制执行操作的最大运行时非常有用。

请注意,这实际上并没有中断该函数 - 它只在完成后进行检查。对于真正的中断,请考虑使用线程。

使用 Time.time 进行速率限制

此示例使用 time.time 来跟踪和控制请求频率,从而实现速率限制。

rate_limit.py
import time

class RateLimiter:
    def __init__(self, calls_per_second):
        self.period = 1.0 / calls_per_second
        self.last_call = 0
    
    def __call__(self, func):
        def wrapper(*args, **kwargs):
            now = time.time()
            elapsed = now - self.last_call
            if elapsed < self.period:
                time.sleep(self.period - elapsed)
            self.last_call = time.time()
            return func(*args, **kwargs)
        return wrapper

@RateLimiter(2)  # 2 calls per second max
def make_api_request():
    print("API request made at", time.strftime("%H:%M:%S"))

for _ in range(5):
    make_api_request()

RateLimiter 装饰器确保包装的函数不会以超过指定速率的频率调用。它会休眠以保持调用之间适当的间隔。

这对于具有速率限制的 API 或任何需要吞吐量控制的操作非常有用。

基于时间的缓存过期

time.time 可以通过将时间戳与缓存的值一起存储来实现缓存过期。此示例展示了一个简单的过期缓存。

expiring_cache.py
import time

class ExpiringCache:
    def __init__(self, ttl_seconds):
        self.cache = {}
        self.ttl = ttl_seconds
    
    def get(self, key):
        item = self.cache.get(key)
        if item and time.time() - item['timestamp'] < self.ttl:
            return item['value']
        return None
    
    def set(self, key, value):
        self.cache[key] = {
            'value': value,
            'timestamp': time.time()
        }

cache = ExpiringCache(5)  # 5 second TTL
cache.set('data', 42)

print(cache.get('data'))  # 42
time.sleep(6)
print(cache.get('data'))  # None (expired)

缓存会在每次获取时检查项目的年龄与当前时间。超过 TTL(生存时间)的项目被认为是过期的并返回 None。

此模式对于临时数据存储非常有用,在这种情况下,新鲜度比持久性更重要。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。到目前为止,我已经撰写了超过 1400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程