user3246402
user3246402

Reputation: 162

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

I have a for loop like :

        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;
        }

and in the clnt.txt file all values are '-2090430839.000000' and on the screen '-2.09043e+09' is written for all time_in_mill1 values. I expected that at least two values are to be different. What am I doing wrong?

Upvotes: 0

Views: 278

Answers (2)

user3246402
user3246402

Reputation: 162

I have just forgetting updating the gettimeofday(). Now every value is different from each other. Thanks for all answers.

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;
     }

Upvotes: 0

kvorobiev
kvorobiev

Reputation: 5070

You need to move gettimeofday into the loop and to correct division

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

Upvotes: 2

Related Questions