1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/nss/lib/freebl/mpi/tests/mptest-4a.c Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,105 @@ 1.4 +/* 1.5 + * mptest4a - modular exponentiation speed test 1.6 + * 1.7 + * This Source Code Form is subject to the terms of the Mozilla Public 1.8 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.9 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.10 + 1.11 +#include <stdio.h> 1.12 +#include <stdlib.h> 1.13 +#include <string.h> 1.14 +#include <limits.h> 1.15 +#include <time.h> 1.16 + 1.17 +#include <sys/time.h> 1.18 + 1.19 +#include "mpi.h" 1.20 +#include "mpprime.h" 1.21 + 1.22 +typedef struct { 1.23 + unsigned int sec; 1.24 + unsigned int usec; 1.25 +} instant_t; 1.26 + 1.27 +instant_t now(void) 1.28 +{ 1.29 + struct timeval clk; 1.30 + instant_t res; 1.31 + 1.32 + res.sec = res.usec = 0; 1.33 + 1.34 + if(gettimeofday(&clk, NULL) != 0) 1.35 + return res; 1.36 + 1.37 + res.sec = clk.tv_sec; 1.38 + res.usec = clk.tv_usec; 1.39 + 1.40 + return res; 1.41 +} 1.42 + 1.43 +extern mp_err s_mp_pad(); 1.44 + 1.45 +int main(int argc, char *argv[]) 1.46 +{ 1.47 + int ix, num, prec = 8; 1.48 + unsigned int d; 1.49 + instant_t start, finish; 1.50 + time_t seed; 1.51 + mp_int a, m, c; 1.52 + 1.53 + seed = time(NULL); 1.54 + 1.55 + if(argc < 2) { 1.56 + fprintf(stderr, "Usage: %s <num-tests> [<precision>]\n", argv[0]); 1.57 + return 1; 1.58 + } 1.59 + 1.60 + if((num = atoi(argv[1])) < 0) 1.61 + num = -num; 1.62 + 1.63 + if(!num) { 1.64 + fprintf(stderr, "%s: must perform at least 1 test\n", argv[0]); 1.65 + return 1; 1.66 + } 1.67 + 1.68 + if(argc > 2) { 1.69 + if((prec = atoi(argv[2])) <= 0) 1.70 + prec = 8; 1.71 + } 1.72 + 1.73 + printf("Test 3a: Modular exponentiation timing test\n" 1.74 + "Precision: %d digits (%d bits)\n" 1.75 + "# of tests: %d\n\n", prec, prec * DIGIT_BIT, num); 1.76 + 1.77 + mp_init_size(&a, prec); 1.78 + mp_init_size(&m, prec); 1.79 + mp_init_size(&c, prec); 1.80 + s_mp_pad(&a, prec); 1.81 + s_mp_pad(&m, prec); 1.82 + s_mp_pad(&c, prec); 1.83 + 1.84 + printf("Testing modular exponentiation ... \n"); 1.85 + srand((unsigned int)seed); 1.86 + 1.87 + start = now(); 1.88 + for(ix = 0; ix < num; ix++) { 1.89 + mpp_random(&a); 1.90 + mpp_random(&c); 1.91 + mpp_random(&m); 1.92 + mp_exptmod(&a, &c, &m, &c); 1.93 + } 1.94 + finish = now(); 1.95 + 1.96 + d = (finish.sec - start.sec) * 1000000; 1.97 + d -= start.usec; d += finish.usec; 1.98 + 1.99 + printf("Total time elapsed: %u usec\n", d); 1.100 + printf("Time per exponentiation: %u usec (%.3f sec)\n", 1.101 + (d / num), (double)(d / num) / 1000000); 1.102 + 1.103 + mp_clear(&c); 1.104 + mp_clear(&a); 1.105 + mp_clear(&m); 1.106 + 1.107 + return 0; 1.108 +}