#include <math.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
char *inttostr_conventional(int n) { | |
char *s = (char*) malloc(sizeof(char) * 42); | |
sprintf(s, "%d", n); | |
return s; | |
} | |
char *inttostr_log(int n) { | |
int len; | |
if (n > 0) { | |
len = (int) floor(log10(n)) + 1; | |
} else if (n == 0) { | |
len = 1; | |
} else if (n < 0) { | |
len = (int) floor(log10(-n)) + 2; | |
} | |
len += 1; | |
char *s = (char*) malloc(sizeof(char) * len); | |
sprintf(s, "%i", n); | |
return s; | |
} | |
char *inttostr_magic(int n) { | |
int len = snprintf((char*) 0, 0, "%i", n) + 1; | |
char *s = (char*) malloc(sizeof(char) * len); | |
snprintf(s, len, "%i", n); | |
return s; | |
} | |
void inttostr_benchmark() { | |
char *s = (char*) 0; | |
for (int i = -1000000; i < 1000000; i++) { | |
s = inttostr_conventional(i); // => 0.365s | |
//s = inttostr_log(i); // => 0.379s | |
//s = inttostr_magic(i); // => 0.544s | |
} | |
} | |
int main() { | |
inttostr_benchmark(); | |
printf("%s", inttostr_magic(42)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment