mulsqr.c (2103B)
1 /* 2 * Test whether to include squaring code given the current settings 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 <limits.h> 11 #include <time.h> 12 13 #define MP_SQUARE 1 /* make sure squaring code is included */ 14 15 #include "mpi.h" 16 #include "mpprime.h" 17 18 int 19 main(int argc, char *argv[]) 20 { 21 int ntests, prec, ix; 22 unsigned int seed; 23 clock_t start, stop; 24 double multime, sqrtime; 25 mp_int a, c; 26 27 seed = (unsigned int)time(NULL); 28 29 if (argc < 3) { 30 fprintf(stderr, "Usage: %s <ntests> <nbits>\n", argv[0]); 31 return 1; 32 } 33 34 if ((ntests = abs(atoi(argv[1]))) == 0) { 35 fprintf(stderr, "%s: must request at least 1 test.\n", argv[0]); 36 return 1; 37 } 38 if ((prec = abs(atoi(argv[2]))) < CHAR_BIT) { 39 fprintf(stderr, "%s: must request at least %d bits.\n", argv[0], 40 CHAR_BIT); 41 return 1; 42 } 43 44 prec = (prec + (DIGIT_BIT - 1)) / DIGIT_BIT; 45 46 mp_init_size(&a, prec); 47 mp_init_size(&c, 2 * prec); 48 49 /* Test multiplication by self */ 50 srand(seed); 51 start = clock(); 52 for (ix = 0; ix < ntests; ix++) { 53 mpp_random_size(&a, prec); 54 mp_mul(&a, &a, &c); 55 } 56 stop = clock(); 57 58 multime = (double)(stop - start) / CLOCKS_PER_SEC; 59 60 /* Test squaring */ 61 srand(seed); 62 start = clock(); 63 for (ix = 0; ix < ntests; ix++) { 64 mpp_random_size(&a, prec); 65 mp_sqr(&a, &c); 66 } 67 stop = clock(); 68 69 sqrtime = (double)(stop - start) / CLOCKS_PER_SEC; 70 71 printf("Multiply: %.4f\n", multime); 72 printf("Square: %.4f\n", sqrtime); 73 if (multime < sqrtime) { 74 printf("Speedup: %.1f%%\n", 100.0 * (1.0 - multime / sqrtime)); 75 printf("Prefer: multiply\n"); 76 } else { 77 printf("Speedup: %.1f%%\n", 100.0 * (1.0 - sqrtime / multime)); 78 printf("Prefer: square\n"); 79 } 80 81 mp_clear(&a); 82 mp_clear(&c); 83 return 0; 84 }