Number of 1 in binary and time comparison

Source: Internet
Author: User
Tags bitwise

public class Algorithm {public static void main (string[] args) {Long T1 = System.currenttimemillis (), for (int i =-1000000 0; 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);} /** * Bitwise operation 1 Number of * * @param x * @return */public static int countone (int x) {x = (x & 0x55555555) + ((x >> 1) &am P 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x & 0x0f0f0f0f) + ((x >> 4) &  0x0f0f0f0f) x = (x & 0x00ff00ff) + ((x >> 8) & 0X00FF00FF);//(1) x = (x & 0x0000ffff) + ((x >> 16) & 0x0000ffff);//(2)//x = (x * 0x01010101) >> (3) return x;} /** * 1 Number * * @param x * @return */public static int countOne2 (int x) {int cnt = 0;while (x! = 0) {x &= (x-1); cnt+ +;} return CNT;}}

Results:





The time of the bitwise operation fluctuates, and the duration of the non-bitwise operation is basically around 250-270. Bit arithmetic is fast indeed.

where (1) and (2) the effect is the same as (3)

Number of 1 in binary and time comparison

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.