JAvaにおけるシフト操作と乗算の違い
現代のプロセッサはこの2つの計算法を最適化すべきで、多くの方法でテストして、送金符号化やテストを見ることができます.
時間が長ければ長いほど正確であることはもちろん100%証明できないが,少なくとも2つの整数の乗算は変位動作と加算の組合せに変換できる点があり,加算と変位動作速度には違いがない.
int arithmetic2 ( int aValue )
{
return aValue * 2;
}
00000030 <arithmetic2>:
30: 55 push %ebp
31: 89 e5 mov %esp,%ebp
33: 8b 45 08 mov 0x8(%ebp),%eax
36: 5d pop %ebp
37: 01 c0 add %eax,%eax
39: c3 ret
int arithmetic3 ( int aValue )
{
return aValue << 1;
}
00000040 <arithmetic3>:
40: 55 push %ebp
41: 89 e5 mov %esp,%ebp
43: 8b 45 08 mov 0x8(%ebp),%eax
46: 5d pop %ebp
47: 01 c0 add %eax,%eax
49: c3 ret
long starttime = System.currentTimeMillis();
for(long i = 0; i < 1000000000; i++) {
int x = 100 << 2;
}
long endtime = System.currentTimeMillis();
System.out.println(endtime - starttime);
long starttime = System.currentTimeMillis();
for(long i = 0; i < 1000000000; i++) {
int x = 100 * 2;
}
long endtime = System.currentTimeMillis();
System.out.println(endtime - starttime);
時間が長ければ長いほど正確であることはもちろん100%証明できないが,少なくとも2つの整数の乗算は変位動作と加算の組合せに変換できる点があり,加算と変位動作速度には違いがない.
int c = 0;
int b = 7;
int a = 5;
while(b!=0) {
if((b & 1) != 0) {
c = c + a;
a <<= 1;
b >>= 1;
}
}
System.out.println(c);