在Windows下获取当前时间,最小单位是1毫秒(即1000纳秒),无法直接获取纳秒级别的精度。如果需要获取纳秒级别的精度,可以借助高精度计时器(High Resolution Timer)来实现。

以下是获取当前时间纳秒级别精度的示例代码:

#include <iostream>
#include <windows.h>

// 获取当前时间,单位为纳秒
long long get_current_time_ns()
{
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);
    return now.QuadPart * 1000000000 / frequency.QuadPart;
}

int main()
{
    long long start = get_current_time_ns();
    // 执行一些耗时的操作
    long long end = get_current_time_ns();
    std::cout << "Time elapsed: " << end - start << " ns" << std::endl;
    return 0;
}

上述代码使用了Windows API中的QueryPerformanceCounterQueryPerformanceFrequency函数,分别用于获取高精度计时器的计数器值和计时器的频率。通过将计数器值乘以10^9再除以频率,即可得到当前时间的纳秒级别精度

CC++ Windows下获取当前时间单位为纳秒

原文地址: https://www.cveoy.top/t/topic/cjwF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录