c - clock_gettime always shows 0 -


i want measure wall clock time clock_gettime every time run code, shows 0. why that? (i want result in miliseconds.)

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <time.h>  int main( int argc, char **argv )   {     struct timespec start, stop;     unsigned long accum;      if( clock_gettime( clock_realtime, &start) == -1 ) {       perror( "clock gettime" );       exit( exit_failure );     }      int i;     for(i=0; i<100000000; i++){int = 3; int b = 100; int c = a*b;}      //system( argv[1] );      if( clock_gettime( clock_realtime, &stop) == -1 ) {       perror( "clock gettime" );       exit( exit_failure );     }      accum = (unsigned long)( (stop.tv_sec - start.tv_sec) * 1000) + (unsigned long)( (stop.tv_nsec - start.tv_nsec) / 1000000 ) +0.5;     printf( "%lu\n", accum );     return( exit_success );   } 

because compiler optimizes away loop. inside loop can't simplified (by compiler is); create result. use (e.g. print) result after loop.

you try switch off optimisation(s) when compile. since current loop easy optimise away, may not make difference.


Comments