2015-04-06 37 views
0

我有一個像環毫秒在for循環中總是相同的:時間在C++

 ofstream myfile; 
     myfile.open ("clnt.txt",std::ofstream::out | std::ofstream::app); 
     struct timeval tv; 
     gettimeofday(&tv, NULL); 
     for(int i=0;i<100;i++) 
     { 
       double time_in_mill1 = 
       (tv.tv_sec) * 1000 + (tv.tv_usec)/1000 ; 
       cout<<time_in_mill1<<endl; 
       int n1=sprintf (den, "%lf", time_in_mill1); 
       printf ("[%s] is a string %d chars long\n",den,n1); 
       myfile << den; 
     } 

,並在clnt.txt文件中的所有值都「-2090430839.000000」並在屏幕上「-2.09043e +09'是爲所有time_in_mill1值寫入的。我預計至少有兩個值是不同的。我究竟做錯了什麼?

+3

您使用整數除法丟失微秒分辨率。所以如果循環在毫秒內完成,所有記錄的時間可能是相同的。或者如果你的系統上的gettimeofday不是很精確。我建議使用'clock_gettime'來代替。 –

+0

謝謝。我試圖從客戶端發送數據包到服務器,我需要測量發送的數據包之間的時間差,我的意思是延遲,如果我使用clock_gettime是否對測量客戶端和服務器中的時間差異很重要? – user3246402

回答

2

你需要移動的gettimeofday進入循環並糾正部門

for(int i=0;i<100;i++) 
{ 
    gettimeofday(&tv, NULL); 
    double time_in_mill1 = 
     (tv.tv_sec) * 1000 + (tv.tv_usec)/1000.0 ; 
    ... 
} 
+0

我已經更改了我的代碼,現在每個值都是'-2089269230.650000'。我認爲for循環在1毫秒內完成。 – user3246402

+0

@ user3246402最有可能的是。您可以將Sleep功能插入到循環中以減慢執行速度。或者只寫一些像(int i = 0; i <1000000; i ++) – kvorobiev

0

我剛纔忘了更新的gettimeofday()。現在每個值都是彼此不同的。感謝所有的答案。

ofstream myfile; 
myfile.open ("clnt.txt",std::ofstream::out | std::ofstream::app); 
struct timeval tv; 
gettimeofday(&tv, NULL); 

    for(int i=0;i<100;i++) 
    { 
       gettimeofday(&tv, NULL); 
       double time_in_mill1 = 
       (tv.tv_sec) * 1000 + (tv.tv_usec)/1000.0 ; 
       cout<<time_in_mill1<<endl; 
       int n1=sprintf (den, "%lf", time_in_mill1); 
       printf ("[%s] is a string %d chars long\n",den,n1); 
       myfile << den; 
    }