调用ctime的time(), c++中不可预测的行为

calling time() of ctime, unpredictable behaviour in c++

本文关键字:不可预测 c++ ctime time 调用      更新时间:2023-10-16

当我在使用ctime lib的项目上工作时,我注意到一个奇怪的错误,我无法理解。过了一会儿,我明白了时间是我烦恼的原因。当使用time()函数时,代码的行为变得不可预测。下面是我编写的示例代码:

1:    #include <ctime>
2:    #include <iostream>
3:    int main(int argc, char argv[])
4:    {
5:       std::cout << "Prova" << std::endl;
6:       time_t  timer1, timer2;
7:       timer1 = time(&timer1);
8:       timer2 = time(&timer2);
9:       while (true){
10:         double leak = difftime(timer2, timer1);
11:         std::cout << "Sleep: " << leak * 1000 << std::endl;
12:         time(&timer1);
13:         time(&timer2);
14:      }
15:      return 0;
16:   }

当尝试调试它时,指令遵循以下顺序:…7 - 8 ->> 7 - 8 ->> 10 - 11>> 10 - 11>> 12 -> 13 - 14>> 8…为什么第7和第8课要重复两次?之前怎么能跳呢?我在Windows 7 64位上使用Visual Studio 2012。只有在发布模式下构建时才会发生这种行为。在调试模式下,所有工作都很好。会是什么呢?有什么是我不知道的还是我弄错了?

编辑:这里有一些类似于我的工作代码。

void System::Run()
{
    time_t  timer1, timer2;
    timer1 = time(&timer1);
    timer2 = time(&timer2);
    while(!mbDone)
    {
      double leak = difftime(timer2, timer1); //I didn't check that is less than 50, but without wait the video go over 40/50 fps
      Sleep(50 - (leak * 1000)); //<- first time I'm expecting to wait nearly 50ms
      time( &timer1 );
      //Other work in between that work fine before
      //Grab image
      //Process image
      //Show image
      time(&timer2);
    }
}

从调试器中我看到,当time()被调用时,值被改变了,但在完成循环之前的某个时刻,它更新了另一次,即使没有调用time

我会尝试调用time(0)而不是传递地址。我不知道time()的内部结构,但是当你传递一个地址时,这个值必须存储两次。传递一个0可以避免这种情况。