Utilice la función gettimeofday en C

Jinku Hu 12 octubre 2023
  1. Utilice la función gettimeofday para calcular el tiempo transcurrido en un bloque de código en C
  2. Utilice la función clock_gettime para calcular el tiempo transcurrido en un bloque de código en C
Utilice la función gettimeofday en C

Este artículo explicará varios métodos para calcular el tiempo transcurrido en un bloque de código utilizando la función gettimeofday en C.

Utilice la función gettimeofday para calcular el tiempo transcurrido en un bloque de código en C

La función gettimeofday es una función compatible con POSIX que recupera la hora actual con una precisión de microsegundos. La función toma dos argumentos; uno es del tipo struct timeval y el otro es struct timezone. Aunque, la estructura timezone se ha depreciado y se debe pasar el valor NULL en su lugar. La estructura timeval, por otro lado, contiene dos miembros, tv_sec y tv_usec, que denota el número de segundos y microsegundos transcurridos desde la Época. El siguiente código de ejemplo demuestra cómo podemos medir el tiempo de ejecución de una sola función: loopFunc.

Generalmente, necesitamos rodear cualquier bloque de código que deba medirse con dos llamadas de gettimeofday, una antes y otra después del bloque. Una vez que la segunda llamada a gettimeofday regresa con éxito, podemos calcular la diferencia de tiempo usando la función definida por el usuario - time_diff. Toma los valores de ambas estructuras timeval y convierte su diferencia en segundos.

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

#define NUM 1000000
#define NUM2 10000000

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

void loopFunc(size_t num) {
  int tmp = 0;
  for (int i = 0; i < num; ++i) {
    tmp += 1;
  }
}

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

  gettimeofday(&start, NULL);
  loopFunc(NUM);
  gettimeofday(&end, NULL);

  printf("loopFunc(%d)  time spent: %0.8f sec\n", NUM, time_diff(&start, &end));

  gettimeofday(&start, NULL);
  loopFunc(NUM2);
  gettimeofday(&end, NULL);

  printf("loopFunc(%d) time spent: %0.8f sec\n", NUM2, time_diff(&start, &end));

  exit(EXIT_SUCCESS);
}

Producción :

loopFunc(1000000)  time spent: 0.00221000 sec
loopFunc(10000000) time spent: 0.02184500 sec

Utilice la función clock_gettime para calcular el tiempo transcurrido en un bloque de código en C

Alternativamente, dado que gettimeofday ha sido marcado como obsoleto desde hace algún tiempo, se recomienda utilizar la función clock_gettime en su lugar. La última función puede recuperar datos de tiempo de diferentes relojes, que se especifican en el primer parámetro. El tipo de reloj común es un reloj de todo el sistema que mide el llamado tiempo de reloj de pared y se identifica mediante la macro CLOCK_REALTIME. El valor de tiempo se almacena en la estructura timespec, que consta de dos miembros que representan el número de segundos y nanosegundos transcurridos desde la Época. Tenga en cuenta que la persona que llama declara el objeto timespec de antemano y su dirección se pasa a la función clock_gettime.

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

#define NUM 1000000
#define NUM2 10000000

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

void loopFunc(size_t num) {
  int tmp = 0;
  for (int i = 0; i < num; ++i) {
    tmp += 1;
  }
}

int main() {
  struct timespec start2;
  struct timespec end2;

  clock_gettime(CLOCK_REALTIME, &start2);
  loopFunc(NUM);
  clock_gettime(CLOCK_REALTIME, &end2);

  printf("loopFunc(%d)  time spent: %0.8f sec\n", NUM,
         time_diff2(&start2, &end2));

  clock_gettime(CLOCK_REALTIME, &start2);
  loopFunc(NUM2);
  clock_gettime(CLOCK_REALTIME, &end2);

  printf("loopFunc(%d) time spent: %0.8f sec\n", NUM2,
         time_diff2(&start2, &end2));

  exit(EXIT_SUCCESS);
}

Producción :

loopFunc(1000000)  time spent: 0.00221000 sec
loopFunc(10000000) time spent: 0.02184500 sec
Autor: 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

Artículo relacionado - C Time