|
| 1 | +#define _GNU_SOURCE |
| 2 | + |
| 3 | +#include <../aes.h> |
| 4 | +#include <../sha256.h> |
| 5 | +#include <assert.h> |
| 6 | +#include <bencher.h> |
| 7 | +#include <stdint.h> |
| 8 | +#include <stdlib.h> |
| 9 | +#include <string.h> |
| 10 | +#include <sys/mman.h> |
| 11 | +#include <time.h> |
| 12 | + |
| 13 | +#define RAND_BOOK_LEN 1024 |
| 14 | + |
| 15 | +typedef struct bench_ctx { |
| 16 | + int* rand_book; |
| 17 | + int rand_idx; |
| 18 | +} bench_ctx_t; |
| 19 | + |
| 20 | +void |
| 21 | +bench_ctx__init(bench_ctx_t* ctx) { |
| 22 | + ctx->rand_book = (int*)malloc(sizeof(int) * RAND_BOOK_LEN); |
| 23 | + for (int i = 0; i < RAND_BOOK_LEN; i++) { |
| 24 | + ctx->rand_book[i] = rand(); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +int |
| 29 | +nop(void* _ctx) { |
| 30 | + (void)_ctx; |
| 31 | + return 0; |
| 32 | +} |
| 33 | + |
| 34 | +int |
| 35 | +bench_sha_1byte(void* _ctx) { |
| 36 | + SHA256_CTX sha; |
| 37 | + volatile uint8_t byte = 0; |
| 38 | + uint8_t hash[32]; |
| 39 | + |
| 40 | + sha256_init(&sha); |
| 41 | + sha256_update(&sha, &byte, 1); |
| 42 | + sha256_final(&sha, hash); |
| 43 | + |
| 44 | + __asm__ __volatile__("" ::"r"(hash)); |
| 45 | + return 0; |
| 46 | +} |
| 47 | + |
| 48 | +int |
| 49 | +bench_sha_32byte(void* _ctx) { |
| 50 | + SHA256_CTX sha; |
| 51 | + uint8_t hash[32]; |
| 52 | + bench_ctx_t* ctx = (bench_ctx_t*)_ctx; |
| 53 | + |
| 54 | + sha256_init(&sha); |
| 55 | + sha256_update(&sha, ctx->rand_book, 32); |
| 56 | + sha256_final(&sha, hash); |
| 57 | + |
| 58 | + __asm__ __volatile__("" ::"r"(hash)); |
| 59 | + return 0; |
| 60 | +} |
| 61 | + |
| 62 | +int |
| 63 | +bench_sha_page(void* _ctx) { |
| 64 | + SHA256_CTX sha; |
| 65 | + uint8_t hash[32]; |
| 66 | + bench_ctx_t* ctx = (bench_ctx_t*)_ctx; |
| 67 | + assert(sizeof(int) * RAND_BOOK_LEN >= 4096); |
| 68 | + |
| 69 | + sha256_init(&sha); |
| 70 | + sha256_update(&sha, ctx->rand_book, 4096); |
| 71 | + sha256_final(&sha, hash); |
| 72 | + |
| 73 | + __asm__ __volatile__("" ::"r"(hash)); |
| 74 | + return 0; |
| 75 | +} |
| 76 | + |
| 77 | +int |
| 78 | +main(int argc, char** argv) { |
| 79 | + srand(time(NULL)); |
| 80 | + bench_ctx_t ctx = {}; |
| 81 | + bench_ctx__init(&ctx); |
| 82 | + |
| 83 | + struct bench benches[] = { |
| 84 | + {.name = "sha 1 byte", |
| 85 | + .init = nop, |
| 86 | + .deinit = nop, |
| 87 | + .iter = bench_sha_1byte}, |
| 88 | + {.name = "sha 32 byte", |
| 89 | + .init = nop, |
| 90 | + .deinit = nop, |
| 91 | + .iter = bench_sha_32byte}, |
| 92 | + {.name = "sha 4096 bytes", |
| 93 | + .init = nop, |
| 94 | + .deinit = nop, |
| 95 | + .iter = bench_sha_page}, |
| 96 | + }; |
| 97 | + struct bench_opts opts = bench_argp(argc, argv); |
| 98 | + run_benches(&opts, benches, sizeof(benches) / sizeof(struct bench), &ctx); |
| 99 | +} |
0 commit comments