gpt4 book ai didi

c++ - 在 Mac OS 上测量 deltatime 毫秒数的最佳方法?

转载 作者:太空狗 更新时间:2023-10-29 20:05:52 27 4
gpt4 key购买 nike

我找到了一个函数来获取自 Mac 启动以来的毫秒数:

U32 Platform::getRealMilliseconds()
{
// Duration is a S32 value.
// if negative, it is in microseconds.
// if positive, it is in milliseconds.
Duration durTime = AbsoluteToDuration(UpTime());
U32 ret;
if( durTime < 0 )
ret = durTime / -1000;
else
ret = durTime;

return ret;
}

问题是大约 20 天后 AbsoluteToDuration 一直返回 INT_MAX,直到 Mac 重新启动。

我尝试使用下面的方法,它有效,但看起来 gettimeofday 需要更多时间并且稍微减慢游戏速度:

timeval tim;
gettimeofday(&tim, NULL);
U32 ret = ((tim.tv_sec) * 1000 + tim.tv_usec/1000.0) + 0.5;

是否有更好的方法来获取自某个纪元(最好是自应用程序启动以来)以来经过的毫秒数?

谢谢!

最佳答案

您真正的问题是您试图将正常运行时间(以毫秒为单位)值放入 32 位整数中。如果您这样做,您的值(value)将始终在 49 天或更短时间内回到零(或饱和),无论您如何获得该值(value)。

一种可能的解决方案是使用 64 位整数来跟踪时间值;这样清算的日子就会推迟几百年,这样你就不用担心这个问题了。这是它的 MacOS/X 实现:

uint64_t GetTimeInMillisecondsSinceBoot()
{
return UnsignedWideToUInt64(AbsoluteToNanoseconds(UpTime()))/1000000;
}

... 或者如果您不想返回 64 位时间值,次优的做法是在程序启动时记录当前的毫秒值,然后始终减去该值从你返回的值。这样,在您自己的程序运行至少 49 天之前,事情不会中断,我认为这对于游戏来说不太可能。

uint32_t GetTimeInMillisecondsSinceProgramStart()
{
static uint64_t _firstTimeMillis = GetTimeInMillisecondsSinceBoot();
uint64_t nowMillis = GetTimeInMillisecondsSinceBoot();
return (uint32_t) (nowMillis-_firstTimeMillis);
}

关于c++ - 在 Mac OS 上测量 deltatime 毫秒数的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10854118/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com