09b8f0a6b768ade4f6bc6af997e65b89e3ddae1c
[tools.git] / perf / randbytes.c
1 /*
2  * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <openssl/rand.h>
13 #include <openssl/crypto.h>
14 #include "perflib/perflib.h"
15
16 #define NUM_CALLS_PER_BLOCK         100
17 #define NUM_CALL_BLOCKS_PER_THREAD  100
18 #define NUM_CALLS_PER_THREAD        (NUM_CALLS_PER_BLOCK * NUM_CALL_BLOCKS_PER_THREAD)
19
20 int err = 0;
21
22 void do_randbytes(size_t num)
23 {
24     int i;
25     unsigned char buf[32];
26
27     for (i = 0; i < NUM_CALLS_PER_THREAD; i++)
28         if (!RAND_bytes(buf, sizeof(buf)))
29             err = 1;
30 }
31
32 int main(int argc, char *argv[])
33 {
34     int threadcount;
35     OSSL_TIME duration;
36     uint64_t us;
37     double avcalltime;
38
39     if (argc != 2) {
40         printf("Usage: randbytes threadcount\n");
41         return EXIT_FAILURE;
42     }
43
44     threadcount = atoi(argv[1]);
45     if (threadcount < 1) {
46         printf("threadcount must be > 0\n");
47         return EXIT_FAILURE;
48     }
49
50     if (!perflib_run_multi_thread_test(do_randbytes, threadcount, &duration)) {
51         printf("Failed to run the test\n");
52         return EXIT_FAILURE;
53     }
54
55     if (err) {
56         printf("Error during test\n");
57         return EXIT_FAILURE;
58     }
59
60     us = ossl_time2us(duration);
61
62     avcalltime = (double)us / (NUM_CALL_BLOCKS_PER_THREAD * threadcount);
63
64     printf("Average time per %d RAND_bytes() calls: %lfus\n",
65            NUM_CALLS_PER_BLOCK, avcalltime);
66
67     return EXIT_SUCCESS;
68 }