You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows平台下Python实现高精度重复函数调用方案咨询

高精度定时调用函数的Windows Python解决方案

方案1:借助pywin32调用Windows高精度定时API

Windows默认定时粒度约16ms,要实现1ms级精度,首先需要调用系统API缩小时钟粒度,再配合高精度计时器控制执行间隔。

  • 步骤:
    1. 安装依赖库:pip install pywin32
    2. 用win32api.timeBeginPeriod(1)将系统定时精度提升至1ms(使用后务必恢复默认)
    3. 基于time.perf_counter()(Python精度最高的计时器)计算执行时间差,确保每次调用间隔稳定

示例代码:

import win32api
import time

def target_func():
    # 替换为你的业务逻辑
    print(f"执行时间:{time.time():.6f}")

def high_precision_timer(interval_ms, func):
    win32api.timeBeginPeriod(1)  # 开启高精度定时模式
    try:
        next_exec_time = time.perf_counter()
        interval_sec = interval_ms / 1000.0
        while True:
            func()
            next_exec_time += interval_sec
            sleep_duration = next_exec_time - time.perf_counter()
            if sleep_duration > 0:
                time.sleep(sleep_duration)
            # 若函数执行超时,直接跳过等待,避免累积误差
    finally:
        win32api.timeEndPeriod(1)  # 恢复系统默认定时粒度

# 启动50Hz(20ms间隔)的定时调用
high_precision_timer(20, target_func)

方案2:用ctypes直接调用Windows原生API

如果不想依赖第三方库,可通过ctypes直接调用kernel32.dll中的系统函数,效果与方案1一致。

示例代码:

import ctypes
import time

# 加载系统库
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

# 定义API函数原型
timeBeginPeriod = kernel32.timeBeginPeriod
timeBeginPeriod.argtypes = [ctypes.c_uint]
timeBeginPeriod.restype = ctypes.c_uint

timeEndPeriod = kernel32.timeEndPeriod
timeEndPeriod.argtypes = [ctypes.c_uint]
timeEndPeriod.restype = ctypes.c_uint

def target_func():
    print(f"执行时间:{time.time():.6f}")

def high_precision_timer(interval_ms, func):
    timeBeginPeriod(1)
    try:
        next_exec_time = time.perf_counter()
        interval_sec = interval_ms / 1000.0
        while True:
            func()
            next_exec_time += interval_sec
            sleep_duration = next_exec_time - time.perf_counter()
            if sleep_duration > 0:
                time.sleep(sleep_duration)
    finally:
        timeEndPeriod(1)

high_precision_timer(20, target_func)

关键注意事项

  • timeBeginPeriod会全局影响系统定时精度,使用完毕必须调用timeEndPeriod恢复,避免额外系统开销
  • 如果目标函数执行时间超过20ms,需将函数逻辑放到独立线程中执行,避免阻塞定时器循环导致间隔失控
  • 正常系统负载下,上述方案可将误差控制在1ms以内,满足你的需求

内容的提问来源于stack exchange,提问作者Tilo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:18:25