gettimeofday() 是否保证具有微秒级分辨率? [英] Is gettimeofday() guaranteed to be of microsecond resolution?

查看:26
本文介绍了gettimeofday() 是否保证具有微秒级分辨率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个最初为 Win32 API 编写的游戏移植到 Linux(嗯,将 Win32 端口的 OS X 端口移植到 Linux).

I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).

我已经通过在进程启动后提供 uSeconds 来实现 QueryPerformanceCounter:

I have implemented QueryPerformanceCounter by giving the uSeconds since the process start up:

BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount)
{
    gettimeofday(&currentTimeVal, NULL);
    performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
    performanceCount->QuadPart *= (1000 * 1000);
    performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);

    return true;
}

这个,加上 QueryPerformanceFrequency() 给出一个常数 1000000 作为频率,在我的机器上运行良好,给我一个包含 的 64 位变量uSeconds 自程序启动以来.

This, coupled with QueryPerformanceFrequency() giving a constant 1000000 as the frequency, works well on my machine, giving me a 64-bit variable that contains uSeconds since the program's start-up.

那么这是否可移植?我不想发现如果内核以某种方式或类似方式编译,它的工作方式会有所不同.然而,我认为它不能移植到 Linux 以外的其他东西.

So is this portable? I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.

推荐答案

也许吧.但是你有更大的问题.gettimeofday() 如果您的系统上有更改计时器的进程(即 ntpd),则可能会导致计时不正确.不过,在普通"Linux 上,我相信 gettimeofday() 的分辨率是 10us.因此,它可以根据系统上运行的进程向前、向后和时间跳跃.这有效地回答了您的问题.

Maybe. But you have bigger problems. gettimeofday() can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a "normal" linux, though, I believe the resolution of gettimeofday() is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no.

您应该查看 clock_gettime(CLOCK_MONOTONIC) 以了解时间间隔.由于多核系统和外部时钟设置等原因,它较少遇到一些问题.

You should look into clock_gettime(CLOCK_MONOTONIC) for timing intervals. It suffers from several less issues due to things like multi-core systems and external clock settings.

另外,查看 clock_getres() 函数.

这篇关于gettimeofday() 是否保证具有微秒级分辨率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆