Post
Topic
Board Wallet software
Re: [ANNOUNCE] picocoin and libccoin -- C-based bitcoin library and client
by
2112
on 28/11/2012, 06:22:56 UTC
It continues to be true for all known compilers I've seen or heard of, when compared with a simple, native machine integer as used by the current implementation.
OK, show of hands. You must have heard of the existience of Microsoft Visual Studio C++/C compiler. I wrote a short test program that tests strong-typed little-endian integer on the Intel architecture, which will be the most important case.
Code:
#include

union le_int {
unsigned char b[4];
int i;
void operator =(int a) { i = a; }
operator int() { return i; }
};

int lehmer1(int n)
{
int r = 1;
while (n--)
r = (16807 * r) % 2147483647;
return r;
}

int lehmer2(int n)
{
union le_int r;

r = 1;
while (n--)
r = (16807 * r) % 2147483647;
return r;
}

void main()
{
printf("%d\n",lehmer1(2112));
printf("%d\n",lehmer2(2112));
}

and the generated "Release Win32" code, with everything at default:

Code:
00311000  push        edi 
printf("%d\n",lehmer1(2112));
00311001  mov         ecx,840h 
00311006  mov         edx,1 
0031100B  mov         edi,7FFFFFFFh 
00311010  imul        edx,edx,41A7h 
00311016  mov         eax,edx 
00311018  cdq 
00311019  idiv        eax,edi 
0031101B  dec         ecx 
0031101C  jne         main+10h (0311010h) 
0031101E  push        edx 
0031101F  push        312100h 
00311024  call        dword ptr ds:[312090h] 
0031102A  add         esp,8 
printf("%d\n",lehmer2(2112));
0031102D  mov         ecx,840h 
00311032  mov         edx,1 
00311037  imul        edx,edx,41A7h 
0031103D  mov         eax,edx 
0031103F  cdq 
00311040  idiv        eax,edi 
00311042  dec         ecx 
00311043  jne         main+37h (0311037h) 
00311045  push        edx 
00311046  push        312100h 
0031104B  call        dword ptr ds:[312090h] 
00311051  add         esp,8

Could anyone here can give an example of a popular compiler that produces different code for those two little functions? Maybe the test program needs to be somehow changed to trip up the optimizer? I'm seriously asking. I have code like this (and pure C equivalent with #define macros instead of operators()) in wide deployment for many years now on a variety of platforms.

I really only have my Windows laptop with me. I would have to ask people to unpack and boot my usual development environment for remote access.

Meanwhile I'm going to see if I can trip-up the Visual Studio somehow by rewriting this code in various ways.