Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
1 /*
2 * mptest-4b.c
3 *
4 * Test speed of a large modular exponentiation of a primitive element
5 * modulo a prime.
6 *
7 * This Source Code Form is subject to the terms of the Mozilla Public
8 * License, v. 2.0. If a copy of the MPL was not distributed with this
9 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <limits.h>
15 #include <time.h>
17 #include <sys/time.h>
19 #include "mpi.h"
20 #include "mpprime.h"
22 char *g_prime =
23 "34BD53C07350E817CCD49721020F1754527959C421C1533244769D4CF060A8B1C3DA"
24 "25094BE723FB1E2369B55FEEBBE0FAC16425161BF82684062B5EC5D7D47D1B23C117"
25 "0FA19745E44A55E148314E582EB813AC9EE5126295E2E380CACC2F6D206B293E5ED9"
26 "23B54EE961A8C69CD625CE4EC38B70C649D7F014432AEF3A1C93";
27 char *g_gen = "5";
29 typedef struct {
30 unsigned int sec;
31 unsigned int usec;
32 } instant_t;
34 instant_t now(void)
35 {
36 struct timeval clk;
37 instant_t res;
39 res.sec = res.usec = 0;
41 if(gettimeofday(&clk, NULL) != 0)
42 return res;
44 res.sec = clk.tv_sec;
45 res.usec = clk.tv_usec;
47 return res;
48 }
50 extern mp_err s_mp_pad();
52 int main(int argc, char *argv[])
53 {
54 instant_t start, finish;
55 mp_int prime, gen, expt, res;
56 unsigned int ix, diff;
57 int num;
59 srand(time(NULL));
61 if(argc < 2) {
62 fprintf(stderr, "Usage: %s <num-tests>\n", argv[0]);
63 return 1;
64 }
66 if((num = atoi(argv[1])) < 0)
67 num = -num;
69 if(num == 0)
70 ++num;
72 mp_init(&prime); mp_init(&gen); mp_init(&res);
73 mp_read_radix(&prime, g_prime, 16);
74 mp_read_radix(&gen, g_gen, 16);
76 mp_init_size(&expt, USED(&prime) - 1);
77 s_mp_pad(&expt, USED(&prime) - 1);
79 printf("Testing %d modular exponentations ... \n", num);
81 start = now();
82 for(ix = 0; ix < num; ix++) {
83 mpp_random(&expt);
84 mp_exptmod(&gen, &expt, &prime, &res);
85 }
86 finish = now();
88 diff = (finish.sec - start.sec) * 1000000;
89 diff += finish.usec; diff -= start.usec;
91 printf("%d operations took %u usec (%.3f sec)\n",
92 num, diff, (double)diff / 1000000.0);
93 printf("That is %.3f sec per operation.\n",
94 ((double)diff / 1000000.0) / num);
96 mp_clear(&expt);
97 mp_clear(&res);
98 mp_clear(&gen);
99 mp_clear(&prime);
101 return 0;
102 }