Tag Archives: C/C++

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

Advertisements

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.

datamodels