Skip to content

Instantly share code, notes, and snippets.

@jeddenlea
Last active January 2, 2016 21:39
Show Gist options
  • Save jeddenlea/8364990 to your computer and use it in GitHub Desktop.
Save jeddenlea/8364990 to your computer and use it in GitHub Desktop.
Shitty PCRE benchmarking
/* Shitty PCRE regexp benchmarking!
* $ gcc -o benchpcre benchpcre.c -ltr -lpcre
* $ ./benchpcre "^f.o$" "foo"
* result: 0
* Without extras:
* 0.060841s elapsed
* With extras:
* 0.058072s elapsed
*/
#include <pcre.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void die(const char *fmt, ...) {
va_list va;
va_start(va, fmt);
vfprintf(stderr, fmt, va);
exit(1);
}
long double diff(const struct timespec *start, const struct timespec *end) {
int64_t s = end->tv_sec;
int64_t n = end->tv_nsec;
long double res;
// "Carry the one"
if (n < start->tv_nsec) {
--s;
n += 1000000000;
}
res = n - start->tv_nsec;
res /= 1000000000;
res += s - start->tv_sec;
return res;
}
void bench(const pcre *re, const pcre_extra* extra, const char* string) {
int x;
int slen = strlen(string);
struct timespec start, end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
for (x = 0; x < 1000000; x++) {
pcre_exec(re, extra, string, slen, 0, 0, NULL, 0);
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
printf("%0.6LFs elapsed\n", diff(&start, &end));
}
int main(int argc, char **argv) {
const char *err = NULL;
int erroff = 0;
pcre *re;
pcre_extra *extra;
int x;
if (argc != 3) {
die("Usage: benchpcre <pattern> <string>\n");
}
re = pcre_compile(argv[1], 0, &err, &erroff, NULL);
if (erroff != 0 || err != NULL) {
die("pcre_compile failed: %d %s\n", erroff, err);
}
extra = pcre_study(re, 0, &err);
if (err != NULL) {
die("pcre_study failed: %s\n", err);
}
printf("result: %d\n", pcre_exec(re, extra, argv[2], strlen(argv[2]), 0, 0, NULL, 0));
printf("Without extras:\n");
bench(re, NULL, argv[2]);
printf("With extras:\n");
bench(re, extra, argv[2]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment