Skip to content

Instantly share code, notes, and snippets.

@guyhughes
Created August 13, 2017 07:00
Show Gist options
  • Save guyhughes/7e97b8788beeca1ca306ce0ef0d9eb19 to your computer and use it in GitHub Desktop.
Save guyhughes/7e97b8788beeca1ca306ce0ef0d9eb19 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <sys/errno.h>
#include <sys/time.h>
#define die(errnum) { errno = errnum; perror(""); exit(1); }
#define xor(rounds) { \
bench(); \
for (r = 0; r < rounds; ++r) \
for (i = 0; i < len_str; ++i) \
pos = i % len_key, str[i] ^= key[pos]; \
benched = bench(); \
printf("%-8d rounds:\t%1.8f\n", rounds, benched);\
}
double bench();
int main(int argc, char **argv, char **envp)
{
uint_fast8_t len_key, len_str, i, pos;
uint_fast32_t r;
char *key, *str;
double benched;
if (argc != 3) {
die(EINVAL);
}
key = argv[1];
str = argv[2];
len_key = strlen(key), len_str = strlen(str);
if (len_key < 1 || len_str < 1) {
die(EINVAL);
}
xor(1);
xor(10);
xor(100);
xor(1000);
xor(10000);
xor(100000);
xor(1000000);
xor(10000000);
}
double bench() {
static struct timeval t = { 0, 0 }, z = { 0, 0};
double result;
if (t.tv_sec == 0) {
gettimeofday(&t, NULL);
return 0.0;
}
gettimeofday(&z, NULL);
result = z.tv_sec - t.tv_sec;
result += (z.tv_usec - t.tv_usec) / 1000000.0;
t.tv_sec = 0;
return result;
}
@guyhughes
Copy link
Author

~
$ ./a.out KEY 'some string'
1        rounds:	0.00000000
10       rounds:	0.00000200
100      rounds:	0.00001100
1000     rounds:	0.00011900
10000    rounds:	0.00116000
100000   rounds:	0.01069500
1000000  rounds:	0.10264700
10000000 rounds:	1.02155000

~
$ ./a.out KEY 'some stupidly long boring oddball string that never really ends'
1        rounds:	0.00000100
10       rounds:	0.00000800
100      rounds:	0.00007700
1000     rounds:	0.00076600
10000    rounds:	0.00744900
100000   rounds:	0.07039500
1000000  rounds:	0.69906600
10000000 rounds:	7.14549000

@guyhughes
Copy link
Author

guyhughes commented Aug 13, 2017

~
$ gcc -O3 benchmark-xor.c

~
$ ./a.out KEY 'some string'
1        rounds:	0.00000000
10       rounds:	0.00000000
100      rounds:	0.00000600
1000     rounds:	0.00004500
10000    rounds:	0.00057400
100000   rounds:	0.00457000
1000000  rounds:	0.04780900
10000000 rounds:	0.41665100

~
$ ./a.out KEY 'some stupidly long boring oddball string that never really ends'
1        rounds:	0.00000000
10       rounds:	0.00000300
100      rounds:	0.00002800
1000     rounds:	0.00027800
10000    rounds:	0.00290900
100000   rounds:	0.02388100
1000000  rounds:	0.26921400
10000000 rounds:	2.40639700

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment