我有一個像環毫秒在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值寫入的。我預計至少有兩個值是不同的。我究竟做錯了什麼?
您使用整數除法丟失微秒分辨率。所以如果循環在毫秒內完成,所有記錄的時間可能是相同的。或者如果你的系統上的gettimeofday不是很精確。我建議使用'clock_gettime'來代替。 –
謝謝。我試圖從客戶端發送數據包到服務器,我需要測量發送的數據包之間的時間差,我的意思是延遲,如果我使用clock_gettime是否對測量客戶端和服務器中的時間差異很重要? – user3246402