Obtaining miliseconds time on Linux

This code allow you to obtain time on Linux in miliseconds. Be aware that measurement of precision time is different on Windows and Linux.

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
    struct timeval start, end;

    long mtime, seconds, useconds;    

    gettimeofday(&start, NULL);
    gettimeofday(&end, NULL);

    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;

    mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

    printf("Elapsed time: %ld milliseconds\n", mtime);

    return 0;

To obtain elapsing time just replace the comment line “//DO SOME TIME-CONSUMING OPERATION" with piece of your code (function, methods, loop, etc.)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s