Learn more about Russian war crimes in Ukraine.

How do I measure program execution time in C? How do I use the times function?

How do you measure the time taken by a program, or a program fragment? The general approach is simple (pseudocode):

time time_thing(f) {
  time t1 = now();
  time t2 = now();
  return t2-t1;

The subtlety is in the semantics of your now function. As it turns out, C has many functions available to get the “current time”. The obvious one is gettimeofday:

#include <sys/time.h>
int gettimeofday(struct timeval *restrict tp, void *restrict tzp);  // The system's notion of the current Greenwich time and the current time zone

But gettimeofday is inappropriate for measuring the running time of your process. gettimeofday measures “wall-clock time”, which means you get a lot of noise due to other system activity, such as other processes and the kernel.

There is another function called times, which has another notion of “current time”: the amount of time “charged” to the current process since it began. The kernel “charges” processes by keeping a counter of how much CPU time they have used.

#include <sys/times.h>
struct tms {
  clock_t tms_utime;  // amount of CPU time charged to current process
  clock_t tms_stime;  // amount of CPU time charged to kernel on behalf of current process
  // ...
void times(struct tms * buf);  // Fill buf with current process charge

Notice the counters distinguish between time charged to the process, and time charged to the kernel on behalf of that process. The latter might include things like: setting up connections, setting up kernel queues.

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.