I'm trying to get the precise execution time for some code i'll use in an experiment in the lab. I was trying some simple code but i'm always getting different execution time. Can you please help me in solving this?
The code i was trying is this
#include <stdio.h> #include <unistd.h> #include <sys/time.h> int main() { long start, end; struct timeval timecheck; gettimeofday(&timecheck, NULL); start = (long)timecheck.tv_sec * 1000 + (long)timecheck.tv_usec / 1000; usleep(200000); // 200ms for (int i = 0; i < 10000000; ++i) {/* code */} gettimeofday(&timecheck, NULL); end = (long)timecheck.tv_sec * 1000 + (long)timecheck.tv_usec / 1000; printf("%ld milliseconds elapsed\n", (end - start)); return 0; } And the results are someting like this
227 milliseconds elapsed
231 milliseconds elapsed
228 milliseconds elapsed
/* code */seem to be discarded, so that the compiler may optimize the code away. You are essentially measuring scheduler delays.