How to Use a Timer in C

Jinku Hu Feb 02, 2024
  1. Use the gettimeofday Function as Timer Benchmark
  2. Use the clock_gettime Function as Timer Benchmark in C
How to Use a Timer in C

This article will introduce multiple methods about how to use a timer in C.

Use the gettimeofday Function as Timer Benchmark

gettimeofday is a POSIX compliant function for retrieving the system time. It takes two arguments, one of the struct timeval type and one of the struct timezone type, the latter of which is obsolete now. Thus, we would need to declare only timeval structures to store retrieved time values. struct timeval consists of two members representing seconds and microseconds, respectively.

In the following example, we implement two functions for finding the maximum value in the array of integers. One of them is based on value comparison, and the other one uses the indices to find the integer with the biggest value. We utilize gettimeofday before and after the max_ function is called to compare the speed of these functions.

Notice that, there is a time_diff function that calculates the elapsed time in seconds. In this case, we only run the test one time on a randomly generated array of integers, but generally, more statistical methods should be used to measure performance in modern systems.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

int max_index(int arr[], int size) {
  size_t max = 0;

  for (int j = 0; j < size; ++j) {
    if (arr[j] > arr[max]) {
      max = j;
    }
  }
  return arr[max];
}

int max_value(int arr[], int size) {
  int max = arr[0];

  for (int j = 0; j < size; ++j) {
    if (arr[j] > max) {
      max = arr[j];
    }
  }
  return max;
}

float time_diff(struct timeval *start, struct timeval *end) {
  return (end->tv_sec - start->tv_sec) + 1e-6 * (end->tv_usec - start->tv_usec);
}

enum { WIDTH = 100000 };

int main() {
  struct timeval start;
  struct timeval end;

  int max;

  int *arr = malloc(WIDTH * sizeof(int));

  srand(time(NULL));
  for (size_t i = 0; i < WIDTH; i++) {
    arr[i] = rand();
  }

  gettimeofday(&start, NULL);
  max = max_index(arr, WIDTH);
  gettimeofday(&end, NULL);

  printf("max_index: %0.8f sec, max = %d\n", time_diff(&start, &end), max);

  gettimeofday(&start, NULL);
  max = max_value(arr, WIDTH);
  gettimeofday(&end, NULL);

  printf("max_value: %0.8f sec, max = %d\n", time_diff(&start, &end), max);

  free(arr);
  exit(EXIT_SUCCESS);
}

Output:

max_index: 0.00028346 sec, max = 2147391322
max_value: 0.00022213 sec, max = 2147391322

Use the clock_gettime Function as Timer Benchmark in C

Alternatively, we can utilize clock_gettime to achieve similar measuring goals. clock_gettime is a more recent and recommended method employed in newer codebases. It stores the time value in the struct timespec object and takes the pointer to it as the second parameter.

Meanwhile, the first argument specifies the type of clock to use. In this example, we retrieve CLOCK_REALTIME because it measures so-called wall-clock time. It is represented as seconds and nanoseconds passed since the epoch, the starting date for time measurement.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

int max_index(int arr[], int size) {
  size_t max = 0;

  for (int j = 0; j < size; ++j) {
    if (arr[j] > arr[max]) {
      max = j;
    }
  }
  return arr[max];
}

int max_value(int arr[], int size) {
  int max = arr[0];

  for (int j = 0; j < size; ++j) {
    if (arr[j] > max) {
      max = arr[j];
    }
  }
  return max;
}

float time_diff2(struct timespec *start, struct timespec *end) {
  return (end->tv_sec - start->tv_sec) + 1e-9 * (end->tv_nsec - start->tv_nsec);
}

enum { WIDTH = 100000 };

int main() {
  struct timespec start2, end2;

  int max;

  int *arr = malloc(WIDTH * sizeof(int));

  srand(time(NULL));
  for (size_t i = 0; i < WIDTH; i++) {
    arr[i] = rand();
  }

  clock_gettime(CLOCK_REALTIME, &start2);
  max = max_index(arr, WIDTH);
  clock_gettime(CLOCK_REALTIME, &end2);

  printf("max_index: %0.8f sec, max = %d\n", time_diff2(&start2, &end2), max);

  clock_gettime(CLOCK_REALTIME, &start2);
  max = max_value(arr, WIDTH);
  clock_gettime(CLOCK_REALTIME, &end2);

  printf("max_value: %0.8f sec, max = %d\n", time_diff2(&start2, &end2), max);

  free(arr);
  exit(EXIT_SUCCESS);
}

Output:

max_index: 0.00028346 sec, max = 2147391322
max_value: 0.00022213 sec, max = 2147391322
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C Time