在for循环中,c++中的时间(以毫秒为单位)始终相同

Time in miliseconds in c++ in a for loop always same

本文关键字:为单位 循环 for c++ 时间      更新时间:2023-10-16

我有一个类似于的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 longn",den,n1);
                myfile << den;
        }

并且在clnt.txt文件中,所有值都是"-2090430839.000000",并且在屏幕上为所有time_in_mill1值写入"-2.09043e+09"。我预计至少有两个值是不同的。我做错了什么?

您需要将gettimeofday移动到循环中,并更正划分

for(int i=0;i<100;i++)
{
    gettimeofday(&tv, NULL);
    double time_in_mill1 = 
      (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000.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 longn",den,n1);
              myfile << den;
     }