首页 > 解决方案 > 如何将调用 QueryPerformanceFrequency 的代码移植到 Rust?

问题描述

我需要将此 C 代码移植到 Rust 中:

QueryPerformanceFrequency((unsigned long long int *) &frequency);

我没有找到这样做的功能。

Linux 变体如下所示:

struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now) == 0)
    frequency = 1000000000;

我应该打电话std::time::Instant::now()并将频率设置为1000000000吗?

这是完整的功能:

// Initializes hi-resolution MONOTONIC timer
static void InitTimer(void)
{
    srand(time(NULL));              // Initialize random seed

    #if defined(_WIN32)
        QueryPerformanceFrequency((unsigned long long int *) &frequency);
    #endif

    #if defined(__linux__)
        struct timespec now;
        if (clock_gettime(CLOCK_MONOTONIC, &now) == 0)
            frequency = 1000000000;
    #endif

    #if defined(__APPLE__)
        mach_timebase_info_data_t timebase;
        mach_timebase_info(&timebase);
        frequency = (timebase.denom*1e9)/timebase.numer;
    #endif

    baseTime = GetTimeCount();      // Get MONOTONIC clock time offset
    startTime = GetCurrentTime();   // Get current time
}

标签: windowstimerust

解决方案


访问 Windows API 的直接解决方案是使用winapicrate。在这种情况下,调用QueryPerformanceFrequency

use std::mem;
use winapi::um::profileapi::QueryPerformanceFrequency;

fn freq() -> u64 {
    unsafe {
        let mut freq = mem::zeroed();
        QueryPerformanceFrequency(&mut freq);
        *freq.QuadPart() as u64
    }
}

fn main() {
    println!("Hello, world!");
}
[dependencies]
winapi = { version = "0.3.8", features = ["profileapi"] }

高分辨率单调定时器

我将Instant用作单调计时器并假设它具有足够高的精度,除非另有证明。


推荐阅读