Created
September 22, 2016 17:36
-
-
Save jstimpfle/a18a724d8d37b60e3bfd8388a934ae4f to your computer and use it in GitHub Desktop.
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
/* benchmark for testing function call overhead of function pointer | |
* integer lexem parsing, vs inlined integer lexem parsing | |
*/ | |
#include <assert.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#define BUFSIZE ((size_t)(1024*1024*1024)) | |
struct timer { | |
struct timespec ts; | |
}; | |
void timer_reset(struct timer *timer) | |
{ | |
int r = clock_gettime(CLOCK_MONOTONIC_RAW, &timer->ts); | |
assert(r == 0); | |
} | |
void timer_print(const char *fmt, struct timer *timer) | |
{ | |
struct timespec now; | |
int r = clock_gettime(CLOCK_MONOTONIC_RAW, &now); | |
assert(r == 0); | |
time_t sec = now.tv_sec - timer->ts.tv_sec; | |
long nsec = now.tv_nsec - timer->ts.tv_nsec; | |
if (nsec < 0) { | |
sec -= 1; | |
nsec += 1000000000; | |
} | |
printf(fmt, (size_t) sec, (size_t) nsec / 1000000); | |
} | |
int intparser(char *c) | |
{ | |
int n = 0; | |
while ('0' <= *c && *c <= '9') | |
n = 10*n + *c++; | |
return n; | |
} | |
void pointerparse(char *buf, size_t sz, int (parser)(char *)) | |
{ | |
char *c = buf; | |
char *end = buf + sz; | |
int sum = 0; | |
while (c + 8 < end) { | |
c[7] = 0; | |
sum += parser(c); | |
c += 8; | |
} | |
printf("sum is %d\n", sum); | |
} | |
void inlineparse(char *buf, size_t sz) | |
{ | |
char *c = buf; | |
char *end = buf + sz; | |
int sum = 0; | |
while (c + 8 <= end) { | |
c[7] = 0; | |
sum += intparser(c); | |
c += 8; | |
} | |
printf("sum is %d\n", sum); | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
if (argc != 2 || (strcmp(argv[1], "function-pointer") != 0 | |
&& strcmp(argv[1], "inline") != 0)) { | |
fprintf(stderr, "usage: %s <function-pointer|inline>\n", | |
argv[0]); | |
exit(1); | |
} | |
int doinline = strcmp(argv[1], "function-pointer") != 0; | |
printf("reading %zd bytes of input\n", BUFSIZE); | |
char *buf = malloc(BUFSIZE); | |
fread(buf, BUFSIZE, 1, stdin); | |
printf("starting \"%s\" parse\n", argv[1]); | |
struct timer timer; | |
timer_reset(&timer); | |
if (doinline) | |
inlineparse(buf, BUFSIZE); | |
else | |
pointerparse(buf, BUFSIZE, intparser); | |
timer_print("parsing time was %zd.%zd\n", &timer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment