I have this tiny library for measuring the execution time in milliseconds and returning the duration plus the result:
execres.h
/******************
* File: execres.h *
******************/
#ifndef EXECRES_H
#define EXECRES_H
#include <sys/time.h>
typedef struct {
unsigned long long millis;
void* result;
} ExecResult, *PExecResult;
PExecResult execTime(void* (*code)(void*), void* param);
#endif /* EXECRES_H */
execres.c
/******************
* File: execres.c *
******************/
#include "execres.h"
#include <stdlib.h>
PExecResult execTime(void* (*code)(void*), void* param)
{
PExecResult result;
struct timeval tva;
struct timeval tvb;
if (!code)
{
return NULL;
}
result = malloc(sizeof(ExecResult));
if (!result)
{
return NULL;
}
gettimeofday(&tva, NULL);
result->result = code(param);
gettimeofday(&tvb, NULL);
result->millis = (unsigned long long)
(tvb.tv_sec * 1000 + tvb.tv_usec / 1000 -
tva.tv_sec * 1000 - tva.tv_usec / 1000);
return result;
}
main.c
/***************
* File: main.c *
***************/
#include <stdint.h>
#include <stdio.h>
#include "execres.h"
static uint64_t Fibonacci(uint64_t n)
{
switch (n)
{
case 0:
return 0;
case 1:
return 1;
default:
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
int main()
{
PExecResult result;
puts("Begin computation.");
result = execTime((void* (*)(void*)) Fibonacci, (void*) 40);
printf("Fibonacci took %u milliseconds and returned %llu.\n",
(unsigned) result->millis,
(uint64_t) result->result);
return 0;
}