Brian Brown
Brian Brown

Reputation: 4311

clock_gettime always shows 0

I want to measure a wall clock time with clock_gettime but every time I run my code, it shows 0. Why is that? (I want my result to be 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 a = 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 );
  }

Upvotes: 2

Views: 1840

Answers (1)

meaning-matters
meaning-matters

Reputation: 22986

Because the compiler optimizes away your loop. Do something inside the loop that can't be simplified easily (by the compiler that is); so create some result. Then use (e.g. print) this result after the loop.

You could also try to switch off optimisation(s) when you compile. But since your current loop is very easy to optimise away, this may not make a difference.

Upvotes: 2

Related Questions