Karim Belabas on Sun, 01 May 2022 16:43:59 +0200 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
Re: question about speed |
* Thomas Kellar [2022-05-01 16:18]: > I have code that looks like the below running billions > of times and the top one is a little faster than the bottom > one. This is not intuitive to me. Is there any explanation? > > if (a == b, > return(0); > ); > return(1); > > why is the above faster: > and the below slower: > > if (a == b, > return(0); > , > return(1); > ); > > Is that always the case? I had the same explanation as Bill. To check my intuition, I ran the following quick test: f() = if (a==b,return(0),return(1)); g() = if (a==b,return(0));return(1); h() = return(a!=b) \\ or (better) 'a != b'; here, timings are the same N = 3*10^6; * a = b = 0: \\ a = b always ? for(i=1,N,f()) time = 474 ms. ? for(i=1,N,g()) time = 950 ms. ? for(i=1,N,h()) time = 327 ms. * a = 1; b = 0: \\ a != b always ? for(i=1,N,f()) time = 529 ms. ? for(i=1,N,g()) time = 436 ms. ? for(i=1,N,h()) time = 323 ms. * a = random(2); b = random(2) : \\ a = b with probability = 1/2 ? for(i=1,N,a=random(2);b=random(2)) \\ basetime time = 1,007 ms. ? for(i=1,N,a=random(2);b=random(2);f()) time = 543 ms. + basetime ? for(i=1,N,a=random(2);b=random(2);g()) time = 721 ms. + basetime ? for(i=1,N,a=random(2);b=random(2);h()) time = 328 ms. + basetime Cheers, K.B. -- Karim Belabas, IMB (UMR 5251) Tel: (+33) (0)5 40 00 26 17 Universite de Bordeaux Fax: (+33) (0)5 40 00 21 23 351, cours de la Liberation http://www.math.u-bordeaux.fr/~kbelabas/ F-33405 Talence (France) http://pari.math.u-bordeaux.fr/ [PARI/GP] `