位操作不高效的时刻

2016-04-19  本文已影响9人  hklbird

题目:

<b>The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2] and Its gray code sequence is:(题目来自Leetcode中的GaryCode)</b>

00 - 0
01 - 1
11 - 3
10 - 2

my last coding :

public List<Integer> grayCode(int n) {
    List<Integer> res = new ArrayList<>();
    int bits = 1;
    res.add(0);
    for(int i=0;i<n;i++)
    {
        bits=1<<i;
        for(int j = res.size()-1;j>=0;j--){
            res.add(res.get(j)|bits);
        }
        
    }
    return res;
}

and it cost me 2ms running in leetcode.
Then the new version :

public List<Integer> grayCode(int n) {
    List<Integer> res = new ArrayList<>();
    int bits = 1;
    res.add(0);
    for(int i=0;i<n;i++)
    {
        bits=1<<i;
        for(int j = res.size()-1;j>=0;j--){
    // change here
            res.add(res.get(j)+bits);
        }
        
    }
    return res;
}

I just use plus instead of or operation,but the runtime now is 1ms.
So I search google to find that <b>mutiply and divide is slower than bit operation.</b>However,there is no files telling me about plus.
So I do the reacher below:

public static void main(String[] args) {
    int res1 = 1000;
    int res2 = 1000;
    int component = 1<<4;
    long startTime1 = System.currentTimeMillis();
    for(long i=0;i<1000000L;i++)
        res1 = res1|component;
    long endTime1 = System.currentTimeMillis();
    long startTime2 = System.currentTimeMillis();
    for(long i=0;i<1000000L;i++)
        res2 = res2+component;
    long endTime2 = System.currentTimeMillis();
    long cost1 = endTime1-startTime1;
    long cost2 = endTime2-startTime2;
    System.out.println("| :"+ (cost1));
    System.out.println("+ :"+cost2);
}

<b>| cost 3ms,but + costs 1ms; We can see | is better than +.</b>
Furthermore,when execution is morethan 100000000,the excution time is nearly the same.
At last ,I draw a conclusion that we use + better.

上一篇 下一篇

猜你喜欢

热点阅读