Time measuring by miliseconds in UNIX – C++

If you want to measure time in miliseconds in Unix, you can use this code. This program returns 2 miliseconds as a result related with usleep function with value of 2000. You can replace your function which you want to measure runtime with this usleep function.

//time measure in miliseconds in Unix
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
using namespace std;



int main(int argc,char* argv[])

{
	struct timeval start, end;
	long mtime, seconds, useconds;

	gettimeofday(&start, NULL);
	usleep(2000);
	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;

}
Tagged , ,

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 )

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

%d bloggers like this: