Created
April 20, 2011 06:21
-
-
Save joeyadams/930486 to your computer and use it in GitHub Desktop.
Benchmarking tool for sort function
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
void sort(const char **strings, size_t count, const char **out); | |
/* Macros grabbed from my darray module: | |
* http://ccan.ozlabs.org/info/darray.html */ | |
#define darray(type) struct {type *item; size_t size; size_t alloc;} | |
#define darray_new() {0,0,0} | |
#define darray_append(arr, ...) do { \ | |
darray_resize(arr, (arr).size+1); \ | |
(arr).item[(arr).size-1] = (__VA_ARGS__); \ | |
} while(0) | |
#define darray_resize(arr, newSize) darray_growalloc(arr, (arr).size = (newSize)) | |
#define darray_realloc(arr, newAlloc) do { \ | |
(arr).item = realloc((arr).item, ((arr).alloc = (newAlloc)) * sizeof(*(arr).item)); \ | |
} while(0) | |
#define darray_growalloc(arr, need) do { \ | |
size_t __need = (need); \ | |
if (__need > (arr).alloc) \ | |
darray_realloc(arr, darray_next_alloc((arr).alloc, __need)); \ | |
} while(0) | |
static inline size_t darray_next_alloc(size_t alloc, size_t need) | |
{ | |
if (alloc == 0) | |
alloc = 1; | |
while (alloc < need) | |
alloc *= 2; | |
return alloc; | |
} | |
static char *chomp(const char *str) | |
{ | |
size_t len; | |
char *ret; | |
len = strlen(str); | |
if (len > 0 && str[len-1] == '\n') | |
len--; | |
ret = malloc(len + 1); | |
memcpy(ret, str, len); | |
ret[len] = '\0'; | |
return ret; | |
} | |
char **get_lines(size_t *count) | |
{ | |
darray(char*) arr = darray_new(); | |
char buffer[1024]; | |
while (fgets(buffer, sizeof(buffer), stdin) != NULL) | |
darray_append(arr, chomp(buffer)); | |
*count = arr.size; | |
return arr.item; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
char **lines; | |
const char **sorted; | |
size_t count; | |
size_t i; | |
int sort_count; | |
int j; | |
if (argc > 1) | |
sort_count = atoi(argv[1]); | |
else | |
sort_count = 1; | |
fprintf(stderr, "Reading lines\n"); | |
lines = get_lines(&count); | |
sorted = malloc(count * sizeof(*sorted)); | |
fprintf(stderr, "Sorting\n"); | |
for (j = 0; j < sort_count; j++) | |
sort((const char **)lines, count, sorted); | |
fprintf(stderr, "Printing\n"); | |
for (i = 0; i < count; i++) | |
puts(sorted[i]); | |
fprintf(stderr, "Freeing\n"); | |
for (i = 0; i < count; i++) | |
free(lines[i]); | |
free(lines); | |
free(sorted); | |
fprintf(stderr, "Done.\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment