我有一个for循环,如:
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值写的。我预计至少有两个值会有所不同。我究竟做错了什么?
答案 0 :(得分: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 ;
...
}
答案 1 :(得分: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;
}