1 #define _POSIX_C_SOURCE 200809L
13 static int run(char** argv
) {
16 if((child
= fork()) == 0) {
17 execvp(argv
[0], argv
);
21 ret
= waitpid(child
, &stat_loc
, 0);
23 return WIFEXITED(stat_loc
) ? 0 : WTERMSIG(stat_loc
);
30 "benchmark N COMMAND [ARGS...]\n"
31 "runs COMMAND (with ARGS) N times and prints timings.\n"
36 #define NANOSECS 1000000000LL
38 long long timespectoll(struct timespec
*ts
) {
39 return ts
->tv_sec
*NANOSECS
+ ts
->tv_nsec
;
42 char *fmt(long long n
) {
44 sprintf(buf
, "%lld.%04lld", n
/NANOSECS
, (n
%NANOSECS
)/(NANOSECS
/1000));
48 int main(int argc
, char** argv
) {
49 if(argc
< 3 || !isdigit(argv
[1][0])) usage();
50 int i
, n
= atoi(argv
[1]);
53 long long *results
= calloc(n
, sizeof *results
);
55 struct timespec b_start
, b_end
;
56 assert(0 == clock_gettime(CLOCK_MONOTONIC
, &b_start
));
58 assert(0 == clock_gettime(CLOCK_MONOTONIC
, &b_end
));
59 results
[i
] = timespectoll(&b_end
) - timespectoll(&b_start
);
61 long long best
= 0x7fffffffffffffffLL
, sum
= 0;
63 if(results
[i
] < best
) best
= results
[i
];
66 printf("called %d times, best result: %ss, avg: %ss, total: %ss\n",
67 n
, fmt(best
), fmt(sum
/(long long)n
), fmt(sum
));