相当于System.DateTime.Now.Ticks的东西

C++ Something that equivalent with System.DateTime.Now.Ticks?

本文关键字:Ticks Now System DateTime 相当于      更新时间:2023-10-16

我刚刚用c#开发游戏,我刚迁移到c++,我只想把游戏重写成c++,并且几乎成功地将所有代码从c#翻译成c++,但是存在一些问题,我的游戏使用c#中的System.DateTime.Now.Ticks…我被卡住了

. .c++中的System.DateTime.Now.Ticks也有类似的功能。

查看这个教程在cplusplus.com获得平台独立。

函数Clock()返回该进程已消耗的tic的数量。要访问此功能,您需要包括:#include <time.h> .

要获得相同的结果,只需以秒为单位,您可以使用CLOCKS_PER_SEC宏,因此您可以执行:Clock() / CLOCKS_PER_SEC来获得此进程所花费的秒数。但请记住,这样做可能会失去一些精度。


你可能不需要这个确切的功能…如果您正在查找自程序启动以来经过的确切时间,则(据我所记得)必须使用difftime()函数。如果您需要精确的抽动,可能会失去一些精度,这取决于您的平台。

这样,您必须在应用程序开始时保存当前时间,并在应用程序期间从当前时间中减去它。

#include <stdio.h>
#include <time.h>
time_t programstart;
int main ()
{
  time(&programstart); //assign the current time 
  /*... the program ...*/
  //get seconds since start
  double secondssincestart = difftime(time(NULL), programstart);
  printf ("the program took: %f secondsn", secondssincestart);
  return 0;
}

编辑:

由于这篇文章仍然受到一些关注,重要的是要注意,今天的c++ 11有标准的,易于使用的,非常方便的库chrono

使用QueryUnbiasedInterruptTime。和DateTime.Ticks一样,QueryUnbiasedInterruptTime的每一秒也是100纳秒。如果你需要更高的分辨率,你需要选择QueryPerformanceCounter

链接:http://msdn.microsoft.com/en-us/library/windows/desktop/ee662306 (v = vs.85) . aspx

没有相应的类或方法,但是您可以这样做:

SYSTEMTIME systemTime;
GetLocalTime(&systemTime);
FILETIME fileTime;
SystemTimeToFileTime(&systemTime, &fileTime);
ULARGE_INTEGER largeInteger;
largeInteger.LowPart = fileTime.dwLowDateTime;
largeInteger.HighPart = fileTime.dwHighDateTime;
ULONGLONG ticks = reinterpret_cast<ULONGLONG&>(largeInteger);

在Windows中使用MFC时,Ticks相当于System.DateTime.Now.Ticks

ULONGLONG GetTicksNow()
{
    COleDateTime epoch(100, 1, 1, 00, 00, 00);
    COleDateTime currTime = COleDateTime::GetCurrentTime();
    COleDateTimeSpan span = currTime - epoch;
    CTimeSpan cSpan(span.GetDays(), span.GetHours(), span.GetMinutes(), 
                                                       span.GetSeconds());
    ULONGLONG diff = cSpan.GetTotalSeconds();
    LONG missingDays = 365 * 99 + 24;
    CTimeSpan centSpan(missingDays, 0, 0, 0);
    ULONGLONG centSeconds = centSpan.GetTotalSeconds();// *1000000000;//
    ULONGLONG totSec = (diff + centSeconds)*10000000;
    return totSec ;
}