Usa un timer in C

Jinku Hu 12 ottobre 2023
  1. Usa la funzione gettimeofday come benchmark del timer
  2. Usa la funzione clock_gettime come benchmark del timer in C
Usa un timer in C

Questo articolo introdurrà più metodi su come utilizzare un timer in C.

Usa la funzione gettimeofday come benchmark del timer

gettimeofday è una funzione compatibile con POSIX per il recupero dell’ora di sistema. Richiede due argomenti, uno del tipo struct timeval e uno del tipo struct timezone, l’ultimo dei quali ora è obsoleto. Quindi, avremmo bisogno di dichiarare solo le strutture timeval per memorizzare i valori di tempo recuperati. struct timeval consiste di due membri che rappresentano rispettivamente secondi e microsecondi.

Nell’esempio seguente, implementiamo due funzioni per trovare il valore massimo nell’array di numeri interi. Uno di questi si basa sul confronto dei valori e l’altro utilizza gli indici per trovare il numero intero con il valore più grande. Usiamo gettimeofday prima e dopo la chiamata della funzione max_ per confrontare la velocità di queste funzioni.

Notare che esiste una funzione time_diff che calcola il tempo trascorso in secondi. In questo caso, eseguiamo il test solo una volta su un array di numeri interi generato in modo casuale, ma in genere dovrebbero essere utilizzati metodi più statistici per misurare le prestazioni nei sistemi moderni.

#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);
}

Produzione:

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

Usa la funzione clock_gettime come benchmark del timer in C

In alternativa, possiamo utilizzare clock_gettime per raggiungere obiettivi di misurazione simili. clock_gettime è un metodo più recente e consigliato utilizzato nelle basi di codici più recenti. Memorizza il valore del tempo nell’oggetto struct timespec e prende il puntatore ad esso come secondo parametro. Nel frattempo, il primo argomento specifica il tipo di orologio da utilizzare. In questo esempio, recuperiamo CLOCK_REALTIME perché misura il cosiddetto tempo dell’orologio da parete. È rappresentato come secondi e nanosecondi trascorsi dall’epoca, la data di inizio per la misurazione del tempo.

#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);
}

Produzione:

max_index: 0.00028346 sec, max = 2147391322
max_value: 0.00022213 sec, max = 2147391322
Autore: 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

Articolo correlato - C Time