Tag Archives: C/C++

Measuring elapsed time

Windows – QueryPerformanceCounter

#include <windows.h> 
using namespace std;

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

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

    return 0;

Linux – gettimeofday

#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 – _SC_CLK_TCK

#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";


$ time ./myprogram

Bash (in script)

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




C++ Data models

A usual headache to C++ beginners: What is the value of sizeof(int) in C/C++?

The answer is: there is no specific answer.

In theory, the C++ standard does not define explicitly the size of primitive data types but it does define their minimum size. You can read more about it at official C++ reference page

In practice though, there are 4 data models that are mostly used : LP32, ILP32, LLP64 and LP64. Both Windows and Linux 32 architectures use ILP32. Windows 64bit use LP64 and Linux 64bit use LLP 64.

If you compare the values, you will see that sizes of all floating point data types are the same regardless of architecture (float 4, double 8, long double 16) and all integer data types are the same apart from long (char 1, short 2, int 4, long long 8). Of course pointers depend on the architecture (32bit in x86 and 64 bit in AMD64)

Here is a handy table for you.