7_R3X
7_R3X

Reputation: 4370

Measuring execution time of a program

The link here says that gettimeofday() sets a structure which contains number of seconds and microseconds since Epoch (please tell me what Epoch is). With that thing in mind I set a structure before and after calling sleep function with parameter 3. So the total time difference setting of these structure is 3 seconds or 3000000 microseconds but it seem to give some wrong output. Where am I getting wrong?

#include<iostream>
#include<ctime>
#include<unistd.h>
#include<cstdio>
#include<sys/time.h>

using namespace std;

int main()
{
    struct timeval start,end;
    gettimeofday(&start,NULL);
    sleep(3);
    gettimeofday(&end,NULL);
    cout<<start.tv_usec<<endl;
    cout<<end.tv_usec<<endl;
    cout<<end.tv_usec-start.tv_usec;
    return 0;
}

Upvotes: 1

Views: 318

Answers (1)

paulsm4
paulsm4

Reputation: 121649

Here's the point you're missing:

unsigned long time_in_micros = 1000000 * tv_sec + tv_usec;

To get the elapsed time in microseconds, you need to ADD "seconds" to "microseconds". You can't just ignore the tv_sec field!

Sample code:

#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main(int argc, char *argv[])
{
    struct timeval start,end;
    gettimeofday(&start,NULL);
    sleep(3);
    gettimeofday(&end,NULL);
    printf ("start: %ld:%ld\n", start.tv_sec, start.tv_usec);
    printf ("end:   %ld:%ld\n", end.tv_sec, end.tv_usec);
    printf ("diff:  %ld:%ld\n",
      end.tv_sec-start.tv_sec, end.tv_usec-start.tv_usec);

    gettimeofday(&start,NULL);
    sleep(10);
    gettimeofday(&end,NULL);
    printf ("start: %ld:%ld\n", start.tv_sec, start.tv_usec);
    printf ("end:   %ld:%ld\n", end.tv_sec, end.tv_usec);
    printf ("diff:  %ld:%ld\n", 
      end.tv_sec-start.tv_sec, end.tv_usec-start.tv_usec);
    return 0;
}

Corresponding output:

start: 1459100430:214715
end:   1459100433:215357
diff:  3:642
start: 1459100433:215394
end:   1459100443:217024
diff:  10:1630

gettimeofday() links:

Upvotes: 1

Related Questions