调用ctime的time(), c++中不可预测的行为
calling time() of ctime, unpredictable behaviour in c++
当我在使用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可以避免这种情况。
相关文章:
- 不可预测的C++睡眠/等待行为
- 超过 N 时出现不可预测的位移结果
- DirectShow CSourceStream::FillBuffer 暂停和查找后对第一帧的不可预测的调用数
- 多线程文件 IO 程序在线程数增加时行为不可预测
- 使用 std::find 查找从二进制文件中读取的字符并转换为 std::vector 中的 std::string<string> 会产生这种不可预测的行为?
- std::sleep_for在Windows 10上的不可预测行为
- 不可预测的文件描述符泄漏
- 循环程序的行为是不可预测的
- C++中不可预测的输出
- 当来自外部库的线程不可预测地崩溃我的应用程序时,我该怎么办
- 不可预测的伪RNG
- C++ 自定义运算符(+=) 的行为方式不可预测
- 如何优化间接基数排序?(又名如何优化不可预测的内存访问模式)
- 修复不可预测的崩溃
- 不可预测的指针行为
- wxWidgets 不可预测的 Seg 故障
- 当 cin.getline() 的第二个参数大于数组长度时,不可预测的字符串长度
- 子表达式求值顺序的不可预测性
- 将QString转换为const-char*时的不可预测的运行时行为
- Qt. QDateTime具有时区和附加秒的不可预测行为