2017-08-16 59 views
-5

我尝试计算通过循环做了多少次操作1秒。 为此,我记得当我开始计算循环并在每次迭代中检查时间时。 我的想法 - 当这两个timemoments的秒数不同时,我printf做了多少循环迭代。错误与参考C++

这里是我的代码:

#include <ctime> 
int main() 
{ 
    // For timing 
    time_t t, tstep; 
    struct tm* now, *step; 

    // this time will change at every iteration 
    t = time(0); 
    now = localtime(&t); 

    // save time of the start moment 
    tstep = t; 
    step = localtime(&tstep); 

    // counter of loop cycles 
    int count = 0; 

    for (size_t i = 0; i < 1e100 ; i++) 
    { 
     // ... here is some calculations  
     t = time(0); 
     now = localtime(&t); 
     count++; 

     if (now->tm_sec != step->tm_sec) 
     { 
      tstep = time(0); 
      step = localtime(&tstep); 
      //printf("number of lines %i \n", count); 
      count = 0; 
     } 
    } 
    return 0; 
} 

是什么问题:我每次刷新nowstep成为相同的值!而ttstep是不同的!

看起来像这是因为引用:也许当我使用tstep = t这意味着这个变量的地址是指t都。因此更改t更改nowtstep

如何解决这个问题?如何将t的值复制到step?或者还有另一种实际的方式?

+0

如果你downvote,你能解释为什么吗? –

+5

“_像这样看是因为参考_”你是**不**在代码中的任何地方使用引用。 –

+1

此外,这不是[最小,完整和可验证的示例](https://stackoverflow.com/help/mcve) – kim366

回答

6

localtime函数不是线程安全的,更重要的是不可重入。

它返回的指针很可能是指向内部static缓冲区的指针。这意味着每个localtime调用都返回指向非常相同的“缓冲区”(结构)的指针。实际上,如果您阅读链接的引用,则可以在多个函数之间共享缓冲区(结构)。

这可以很容易地通过调试器检查并比较函数返回的指针。

如果您需要不同的值,那么您需要复制数据而不是复制指针。这只需通过使nowstep结构实例而不是指针来完成。然后取消引用由localtime返回的指针:

struct tm now, step; // Note: Not pointers! 

... 

now = *localtime(&t); // Dereference returned pointer 
+1

谢谢您的同情!我对通过评论和评论倾注于我的消极情绪感到非常惊讶,很高兴有人想到如何提供帮助,而不是如何捣乱:) –