Last active
December 18, 2015 04:29
-
-
Save manucorporat/5726177 to your computer and use it in GitHub Desktop.
Smart way to profile algorithms in C.
Full project with examples coming soon!!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdbool.h> | |
#include <sys/time.h> | |
typedef struct _profile_buf { | |
const char *title; | |
unsigned long long total; | |
unsigned long long index; | |
struct timeval timestamp; | |
} profile_buf; | |
inline profile_buf __initProfile(const char *title, unsigned long long total) | |
{ | |
profile_buf state; | |
state.title = title; | |
state.total = total; | |
state.index = 0; | |
gettimeofday(&state.timestamp, NULL); | |
return state; | |
} | |
inline bool __profile(profile_buf *state) | |
{ | |
if(state->index != state->total) | |
return true; | |
else | |
{ | |
struct timeval now; | |
gettimeofday(&now, NULL); | |
unsigned long long totalTime = (now.tv_sec - state->timestamp.tv_sec)*1000000 + (now.tv_usec - state->timestamp.tv_usec); | |
double iterationTime = (double)totalTime/(double)state->total; | |
printf( | |
"%s:\n" | |
" - Iterations: %llu\n" | |
" - Total time: %llu μs (%f s)\n" | |
" - Iteration time: %f μs (%f s)\n\n", | |
state->title, | |
state->total, | |
totalTime, (totalTime/1000000.0), | |
iterationTime, (iterationTime/1000000.0)); | |
return false; | |
} | |
} | |
#define PROFILE_N(__TEXT__, __TOTAL__) \ | |
for(profile_buf buff = __initProfile(__TEXT__, __TOTAL__); __profile(&buff); ++buff.index) | |
#define PROFILE(__TEXT__) PROFILE_N(__TEXT__, 100000000) | |
/************** USAGE *************** | |
int main() { | |
volatile int value; | |
PROFILE("ALGORITHM 1, SQRT") { | |
value += sqrt(value); | |
} | |
PROFILE("ALGORITHM 2, ADDITION") { | |
value += 3; | |
} | |
return value; //prevent lazy optimations | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment