Why set zero in zero.c rather than use xor_n

Win C winsto003 at hotmail.com
Mon Feb 5 09:41:24 UTC 2018


Hi! There are a lot of reports that using xor is faster than setting a variable to zero. Therefore, I did a little test with the following code:


#include "gmp.h"

#include <stdio.h>

#include <time.h>

#include <stdlib.h>


int main()

{

int i;

mp_limb_t *pi = malloc(16);

time_t t = clock();

for ( i = 0; i < 1000000; ++i )

mpn_zero(pi, 4);

printf("%ld\n", clock() - t);

t = clock();

for ( i = 0; i < 1000000; ++i )

                mpn_xor_n(pi, pi, pi, 4);

        printf("%ld\n", clock() - t);

}


And to my surprise, the results are as follows:


1st run:

$./zeroing

73491

17651


2nd run:

$./zeroing

78131

17592


3rd run:

$./zeroing

77434

17584


It clearly shows that using xor_n is faster than setting zero!

So should we change the code like this?


--- a/mpn/generic/zero.c        Fri Feb 02 17:00:53 2018 +0100

+++ b/mpn/generic/zero.c        Mon Feb 05 17:19:43 2018 +0800

@@ -33,9 +33,5 @@

 void

 mpn_zero (mp_ptr rp, mp_size_t n)

 {

-  mp_size_t i;

-

-  rp += n;

-  for (i = -n; i != 0; i++)

-    rp[i] = 0;

+  mpn_xor_n(rp, rp, rp, n);

 }


How do you guys think? Thanks!


More information about the gmp-devel mailing list