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

查看:133
本文介绍了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作为频率,在我的机器上效果很好,自程序启动以来,我得到了一个包含uSeconds的64位变量.

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.

推荐答案

也许.但是你有更大的问题.如果系统上的某些进程更改了计时器(例如ntpd),则gettimeofday()可能会导致错误的计时.但是,在普通" 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天全站免登陆