security/nss/lib/freebl/mpi/utils/metime.c

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:4dc35319ec78
1 /*
2 * metime.c
3 *
4 * Modular exponentiation timing test
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <limits.h>
14 #include <time.h>
15
16 #include "mpi.h"
17 #include "mpprime.h"
18
19 double clk_to_sec(clock_t start, clock_t stop);
20
21 int main(int argc, char *argv[])
22 {
23 int ix, num, prec = 8;
24 unsigned int seed;
25 clock_t start, stop;
26 double sec;
27
28 mp_int a, m, c;
29
30 if(getenv("SEED") != NULL)
31 seed = abs(atoi(getenv("SEED")));
32 else
33 seed = (unsigned int)time(NULL);
34
35 if(argc < 2) {
36 fprintf(stderr, "Usage: %s <num-tests> [<nbits>]\n", argv[0]);
37 return 1;
38 }
39
40 if((num = atoi(argv[1])) < 0)
41 num = -num;
42
43 if(!num) {
44 fprintf(stderr, "%s: must perform at least 1 test\n", argv[0]);
45 return 1;
46 }
47
48 if(argc > 2) {
49 if((prec = atoi(argv[2])) <= 0)
50 prec = 8;
51 else
52 prec = (prec + (DIGIT_BIT - 1)) / DIGIT_BIT;
53
54 }
55
56 printf("Modular exponentiation timing test\n"
57 "Precision: %d digits (%d bits)\n"
58 "# of tests: %d\n\n", prec, prec * DIGIT_BIT, num);
59
60 mp_init_size(&a, prec);
61 mp_init_size(&m, prec);
62 mp_init_size(&c, prec);
63
64 srand(seed);
65
66 start = clock();
67 for(ix = 0; ix < num; ix++) {
68
69 mpp_random_size(&a, prec);
70 mpp_random_size(&c, prec);
71 mpp_random_size(&m, prec);
72 /* set msb and lsb of m */
73 DIGIT(&m,0) |= 1;
74 DIGIT(&m, USED(&m)-1) |= (mp_digit)1 << (DIGIT_BIT - 1);
75 if (mp_cmp(&a, &m) > 0)
76 mp_sub(&a, &m, &a);
77
78 mp_exptmod(&a, &c, &m, &c);
79 }
80 stop = clock();
81
82 sec = clk_to_sec(start, stop);
83
84 printf("Total: %.3f seconds\n", sec);
85 printf("Individual: %.3f seconds\n", sec / num);
86
87 mp_clear(&c);
88 mp_clear(&a);
89 mp_clear(&m);
90
91 return 0;
92 }
93
94 double clk_to_sec(clock_t start, clock_t stop)
95 {
96 return (double)(stop - start) / CLOCKS_PER_SEC;
97 }
98
99 /*------------------------------------------------------------------------*/
100 /* HERE THERE BE DRAGONS */

mercurial