Time in milliseconds in C Time in milliseconds in C c c

Time in milliseconds in C


Yes, this program has likely used less than a millsecond. Try using microsecond resolution with timeval.

e.g:

#include <sys/time.h>struct timeval stop, start;gettimeofday(&start, NULL);//do stuffgettimeofday(&stop, NULL);printf("took %lu us\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec); 

You can then query the difference (in microseconds) between stop.tv_usec - start.tv_usec. Note that this will only work for subsecond times (as tv_usec will loop). For the general case use a combination of tv_sec and tv_usec.

Edit 2016-08-19

A more appropriate approach on system with clock_gettime support would be:

struct timespec start, end;clock_gettime(CLOCK_MONOTONIC_RAW, &start);//do stuffclock_gettime(CLOCK_MONOTONIC_RAW, &end);uint64_t delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;


This code snippet can be used for displaying time in seconds,milliseconds and microseconds:

#include <sys/time.h>struct timeval start, stop;double secs = 0;gettimeofday(&start, NULL);// Do stuff  heregettimeofday(&stop, NULL);secs = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec - start.tv_sec);printf("time taken %f\n",secs);


A couple of things might affect the results you're seeing:

  1. You're treating clock_t as a floating-point type, I don't think it is.
  2. You might be expecting (1^4) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.
  3. Since the XOR is of constants, it's probably folded by the compiler, meaning it doesn't add a lot of work at runtime.
  4. Since the output is buffered (it's just formatting the string and writing it to memory), it completes very quickly indeed.

You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.

If you have it, try adding a call to sleep() between the start/stop snapshots. Note that sleep() is POSIX though, not standard C.