Long.numberOfTrailingZeros()的Java实现

时间:2011-06-28 12:26:48

标签: java algorithm

文档链接:http://download.oracle.com/javase/6/docs/api/java/lang/Long.html#numberOfTrailingZeros%28long%29

这是Java实现源代码:

/**
 * Returns the number of zero bits following the lowest-order ("rightmost")
 * one-bit in the two's complement binary representation of the specified
 * <tt>long</tt> value.  Returns 64 if the specified value has no
 * one-bits in its two's complement representation, in other words if it is
 * equal to zero.
 *
 * @return the number of zero bits following the lowest-order ("rightmost")
 *     one-bit in the two's complement binary representation of the
 *     specified <tt>long</tt> value, or 64 if the value is equal
 *     to zero.
 * @since 1.5
 */
public static int numberOfTrailingZeros(long i) {
    // HD, Figure 5-14
int x, y;
if (i == 0) return 64;
int n = 63;
y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
y = x <<16; if (y != 0) { n = n -16; x = y; }
y = x << 8; if (y != 0) { n = n - 8; x = y; }
y = x << 4; if (y != 0) { n = n - 4; x = y; }
y = x << 2; if (y != 0) { n = n - 2; x = y; }
return n - ((x << 1) >>> 31);
}

此算法将长时间分解为两个整数并处理每个int。我的问题是为什么不使用y = x&lt;&lt; 32而不是分开多长时间?

这是我的版本:

public static int bit(long i)
{
    if (i == 0) return 64;
    long x = i;
    long y;
    int n = 63;
    y = x << 32; if (y != 0) { n -= 32; x = y; }
    y = x << 16; if (y != 0) { n -= 16; x = y; }
    y = x <<  8; if (y != 0) { n -=  8; x = y; }
    y = x <<  4; if (y != 0) { n -=  4; x = y; }
    y = x <<  2; if (y != 0) { n -=  2; x = y; }
    return (int) (n - ((x << 1) >>> 63));
}

我测试了两种方法并取平均值。实现时间:595,我的版本时间:593。也许原始实现在32位系统上更快,因为我使用的是Windows 7 64位。至少Java应该在x64 sdk中使用类似我的版本。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

几乎每个应用程序都可以忽略0.5%的性能差异。如果您使用一个需要查看此单一方法的应用程序,则可以自行实现。

答案 1 :(得分:1)

In recent versions of Java, say Java 8, such functions are intrinsics.

http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/share/vm/classfile/vmSymbols.hpp#l681