Comparison of the number and time of 1 in binary
Public class Algorithm {public static void main (String [] args) {long t1 = System. currentTimeMillis (); for (int I =-10000000; I <10000000; I ++) {countOne (I) ;}long t2 = System. currentTimeMillis (); long p1 = t2-t1; long t3 = System. currentTimeMillis (); for (int I =-10000000; I <10000000; I ++) {countOne2 (I) ;} long t4 = System. currentTimeMillis (); long p2 = t4-t3; System. out. println (p1 + "----" + p2 );} /*** Calculate the number of bits in 1 ** @ param x * @ return */public static int countOne (int x) {x = (x & 0x55555555) + (x> 1) & 0x55555555); x = (x & 0x33333333) + (x> 2) & 0x33333333 ); x = (x & 0x0f0f0f) + (x> 4) & 0x0f0f0f); x = (x & 0x00ff00ff) + (x> 8) & 0x00ff00ff ); // (1) x = (x & 0x0000ffff) + (x> 16) & 0x0000ffff); // (2) // x = (x * 0x01010101)> 24; (3) return x;}/*** number of 1 ** @ param x * @ return */Public static int countOne2 (int x) {int cnt = 0; while (x! = 0) {x & = (x-1); cnt ++;} return cnt ;}}
Result:
The time of bitwise operations fluctuates, and the time of non-bitwise operations is about. Bit operations are indeed fast.
The effects of (1) and (2) are the same as those of (3 ).