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

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