Skip to content

Instantly share code, notes, and snippets.

@coderodde
Created May 30, 2016 13:49
Show Gist options
  • Save coderodde/586c57d77435010213d5147a6a15076f to your computer and use it in GitHub Desktop.
Save coderodde/586c57d77435010213d5147a6a15076f to your computer and use it in GitHub Desktop.
/******************
* File: execres.c *
******************/
#include "execres.h"
#include <stdlib.h>
PExecResult execTime( void* (*code)( void*), void* param ){
PExecResult result = (PExecResult) malloc( sizeof(ExecResult) );
#ifdef __GNUC__
struct timeval tva;
struct timeval tvb;
#elif defined _MSC_VER
DWORD dwa;
DWORD dwb;
#endif
if( result == NULL || code == NULL ) return NULL;
#ifdef __GNUC__
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
);
#elif defined _MSC_VER
dwa = GetTickCount();
result->result = code( param );
dwb = GetTickCount();
result->millis = (unsigned long long)( dwb - dwa );
#endif
return result;
}
/******************
* File: execres.h *
******************/
#ifndef EXECRES_H
#define EXECRES_H
#ifdef __GNUC__
# include <sys/time.h>
#else
# error Environment not supported.
#endif
typedef struct {
unsigned long long millis;
void* result;
} ExecResult, *PExecResult;
PExecResult execTime(void* (*code)(void*), void* param);
#endif /* EXECRES_H */
/***************
* 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 = execTime((void* (*)(void*)) Fibonacci, (void*) 40);
printf("Fibonacci took %u milliseconds and returned %llu.",
(unsigned) result->millis,
(uint64_t) result->result);
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment