| 1 | #include "test-tool.h" |
| 2 | #include "hash.h" |
| 3 | |
| 4 | #define NUM_SECONDS 3 |
| 5 | |
| 6 | static inline void compute_hash(const struct git_hash_algo *algo, struct git_hash_ctx *ctx, uint8_t *final, const void *p, size_t len) |
| 7 | { |
| 8 | algo->init_fn(ctx); |
| 9 | git_hash_update(ctx, p, len); |
| 10 | git_hash_final(final, ctx); |
| 11 | } |
| 12 | |
| 13 | int cmd__hash_speed(int ac, const char **av) |
| 14 | { |
| 15 | struct git_hash_ctx ctx; |
| 16 | unsigned char hash[GIT_MAX_RAWSZ]; |
| 17 | clock_t initial, start, end; |
| 18 | unsigned bufsizes[] = { 64, 256, 1024, 8192, 16384 }; |
| 19 | void *p; |
| 20 | const struct git_hash_algo *algo = NULL; |
| 21 | |
| 22 | if (ac == 2) { |
| 23 | for (size_t i = 1; i < GIT_HASH_NALGOS; i++) { |
| 24 | if (!strcmp(av[1], hash_algos[i].name)) { |
| 25 | algo = &hash_algos[i]; |
| 26 | break; |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | if (!algo) |
| 31 | die("usage: test-tool hash-speed algo_name"); |
| 32 | |
| 33 | /* Use this as an offset to make overflow less likely. */ |
| 34 | initial = clock(); |
| 35 | |
| 36 | printf("algo: %s\n", algo->name); |
| 37 | |
| 38 | for (size_t i = 0; i < ARRAY_SIZE(bufsizes); i++) { |
| 39 | unsigned long j, kb; |
| 40 | double kb_per_sec; |
| 41 | p = xcalloc(1, bufsizes[i]); |
| 42 | start = end = clock() - initial; |
| 43 | for (j = 0; ((end - start) / CLOCKS_PER_SEC) < NUM_SECONDS; j++) { |
| 44 | compute_hash(algo, &ctx, hash, p, bufsizes[i]); |
| 45 | |
| 46 | /* |
| 47 | * Only check elapsed time every 128 iterations to avoid |
| 48 | * dominating the runtime with system calls. |
| 49 | */ |
| 50 | if (!(j & 127)) |
| 51 | end = clock() - initial; |
| 52 | } |
| 53 | kb = j * bufsizes[i]; |
| 54 | kb_per_sec = kb / (1024 * ((double)end - start) / CLOCKS_PER_SEC); |
| 55 | printf("size %u: %lu iters; %lu KiB; %0.2f KiB/s\n", bufsizes[i], j, kb, kb_per_sec); |
| 56 | free(p); |
| 57 | } |
| 58 | |
| 59 | return 0; |
| 60 | } |