|
1 /* |
|
2 * mptest4a - modular exponentiation speed test |
|
3 * |
|
4 * This Source Code Form is subject to the terms of the Mozilla Public |
|
5 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
7 |
|
8 #include <stdio.h> |
|
9 #include <stdlib.h> |
|
10 #include <string.h> |
|
11 #include <limits.h> |
|
12 #include <time.h> |
|
13 |
|
14 #include <sys/time.h> |
|
15 |
|
16 #include "mpi.h" |
|
17 #include "mpprime.h" |
|
18 |
|
19 typedef struct { |
|
20 unsigned int sec; |
|
21 unsigned int usec; |
|
22 } instant_t; |
|
23 |
|
24 instant_t now(void) |
|
25 { |
|
26 struct timeval clk; |
|
27 instant_t res; |
|
28 |
|
29 res.sec = res.usec = 0; |
|
30 |
|
31 if(gettimeofday(&clk, NULL) != 0) |
|
32 return res; |
|
33 |
|
34 res.sec = clk.tv_sec; |
|
35 res.usec = clk.tv_usec; |
|
36 |
|
37 return res; |
|
38 } |
|
39 |
|
40 extern mp_err s_mp_pad(); |
|
41 |
|
42 int main(int argc, char *argv[]) |
|
43 { |
|
44 int ix, num, prec = 8; |
|
45 unsigned int d; |
|
46 instant_t start, finish; |
|
47 time_t seed; |
|
48 mp_int a, m, c; |
|
49 |
|
50 seed = time(NULL); |
|
51 |
|
52 if(argc < 2) { |
|
53 fprintf(stderr, "Usage: %s <num-tests> [<precision>]\n", argv[0]); |
|
54 return 1; |
|
55 } |
|
56 |
|
57 if((num = atoi(argv[1])) < 0) |
|
58 num = -num; |
|
59 |
|
60 if(!num) { |
|
61 fprintf(stderr, "%s: must perform at least 1 test\n", argv[0]); |
|
62 return 1; |
|
63 } |
|
64 |
|
65 if(argc > 2) { |
|
66 if((prec = atoi(argv[2])) <= 0) |
|
67 prec = 8; |
|
68 } |
|
69 |
|
70 printf("Test 3a: Modular exponentiation timing test\n" |
|
71 "Precision: %d digits (%d bits)\n" |
|
72 "# of tests: %d\n\n", prec, prec * DIGIT_BIT, num); |
|
73 |
|
74 mp_init_size(&a, prec); |
|
75 mp_init_size(&m, prec); |
|
76 mp_init_size(&c, prec); |
|
77 s_mp_pad(&a, prec); |
|
78 s_mp_pad(&m, prec); |
|
79 s_mp_pad(&c, prec); |
|
80 |
|
81 printf("Testing modular exponentiation ... \n"); |
|
82 srand((unsigned int)seed); |
|
83 |
|
84 start = now(); |
|
85 for(ix = 0; ix < num; ix++) { |
|
86 mpp_random(&a); |
|
87 mpp_random(&c); |
|
88 mpp_random(&m); |
|
89 mp_exptmod(&a, &c, &m, &c); |
|
90 } |
|
91 finish = now(); |
|
92 |
|
93 d = (finish.sec - start.sec) * 1000000; |
|
94 d -= start.usec; d += finish.usec; |
|
95 |
|
96 printf("Total time elapsed: %u usec\n", d); |
|
97 printf("Time per exponentiation: %u usec (%.3f sec)\n", |
|
98 (d / num), (double)(d / num) / 1000000); |
|
99 |
|
100 mp_clear(&c); |
|
101 mp_clear(&a); |
|
102 mp_clear(&m); |
|
103 |
|
104 return 0; |
|
105 } |