替代GetSystemTime()以跟踪传递的时间

时间:2015-01-24 14:26:20

标签: c++ windows time windows-7 countdown

我试图在经过一段特定时间后使用一个函数(下面的例子中的doAction()函数)。在下面的例子中,我必须使用该函数10次,在进入'while循环'后第一次是1毫秒,第二次是在进入'while循环'后3秒,依此类推。

简单地说,我需要一种方法来测量从'while循环'开始到任何给定时刻的时间,以便我可以在特定的时刻应用doAction()函数。

问题:我可以使用哪种方法来跟踪初始时刻和之后的任何其他时刻之间经过的时间? 已编辑:我正在使用Windows 7

目前我使用GetSystemTime()函数进行以下设置,虽然有一些问题:

int countVar = 0;
int timeList[10] = {1, 3, 6, 7, 9, 11, 14, 15, 17, 19};
    /*values representing milliseconds after initiating the while loop*/

SYSTEMTIME timeBuffer;
GetSystemTime(&timeBuffer);
int initialTime = timeBuffer.wMilliseconds + (timeBuffer.wSecond*1000) + (timeBuffer.wMinute*60000);
int currentTime;

while (true)
{
   GetSystemTime(&timeBuffer);
   currentTime = timeBuffer.wMilliseconds + (timeBuffer.wSecond*1000) + (timeBuffer.wMinute*60000) - initialTime;

   if (currentTime >= timeList(countVar)
   {
      doAction();
      if (countVar!=9)
      countVar++;
      else
      break;

   }

}

doAction函数只是一个非常快速的函数,不会对时间产生重大影响。

void doAction()  /*this is the action done which is completed in 
                 microseconds hence would not have a significant
                 delay in time*/
{
   ....
}

此设置存在的问题如下:

1)如果系统时间是59分59秒,那么下一个我要查找的系统时间将超过59分59秒,除非我还包括计算中的wHours,否则我无法获得该系统时间,并且可以说数天和数周等等。

2)我更喜欢使用一个函数,当使用时,开始向下计数毫秒,并且当重用该函数时会告诉我自倒计时开始以来已经使用了多少毫秒。但是我还没有在msdn中找到这样的函数。

如果有人能指出我使用比GetSystemTime()更好的函数的方向来衡量一定时刻过去了多少时间,那就太棒了!

编辑: 我使用的是Windows 7

1 个答案:

答案 0 :(得分:0)

如果您使用的是C ++ 11,则可以:

包括chrono

std :: chrono :: system_clock :: time_point starts;

starts = std :: chrono :: system_clock :: now();

在这里做你的东西......

auto ends = std :: chrono :: system_clock :: now();

auto elapsed = std :: chrono :: duration_cast(ends - starts);

这将为您提供以秒为单位的经过时间。