2017-08-16 80 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

謝謝您的同情!我對通過評論和評論傾注於我的消極情緒感到非常驚訝,很高興有人想到如何提供幫助,而不是如何搗亂:) –