Measuring elapsed time

Windows

#include <windows.h> 
...   
using namespace std;

int main() {
    LARGE_INTEGER f;      // ticks per second
    LARGE_INTEGER t1, t2; // ticks
    double dt;

    QueryPerformanceFrequency(&f);
    QueryPerformanceCounter(&t1);
    // ... do stuff
    QueryPerformanceCounter(&t2);
    
    dt = (t2.QuadPart-t1.QuadPart)*1000.0/f.QuadPart;
    cout << elapsedTime << " ms.\n";

    return 0;
}

Linux

#include <sys/time.h>
...
using namespace std;

int main() {
    struct timeval t1, t2;
    double dt;
    
    gettimeofday(&t1, NULL);
    // ... do stuff   
    gettimeofday(&t2, NULL);

    // sec to ms
    dt = (t2.tv_sec - t1.tv_sec) * 1000.0; 
     
    // us to ms
    dt += (t2.tv_usec - t1.tv_usec) / 1000.0; 
  
    cout << dt << " ms.\n";

    return 0;
}

Linux – another way

#include <sys/times.h> 
#include <unistd.h>
...
using namespace std;

int main( void ) {
    double t1, t2, cpu_time, run_time;
    struct tms tb1, tb2;
    double ticspersec;
    int i, sum = 0;

    ticspersec = (double) sysconf(_SC_CLK_TCK);

    t1 = (double) times(&tb1);
    // do stuff
    t2 = (double) times(&tb2);

    cpu_time = (double) ((tb2.tms_utime + tb2.tms_stime) -(tb1.tms_utime + tb1.tms_stime));
    run_time = (t2 - t1) / ticspersec;

    cout << cpu_time << " sec.\n";
    cout << run_time << " sec.\n";
}

Bash

$ time ./myprogram

Bash (in script)

start=$SECONDS
# ... do stuff
end=$SECONDS
dt=$(( end - start ))
echo "stuff took $dt seconds to complete"

References:

https://stackoverflow.com/questions/14682824/measuring-elapsed-time-in-linux-for-a-c-program

https://stackoverflow.com/questions/2150291/how-do-i-measure-a-time-interval-in-c

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s