Java 中的“快速”整数幂

2024-01-07

[简短回答:糟糕的基准测试方法。你可能认为我现在已经明白了。]

该问题被表述为“找到一种快速计算x^y的方法,其中x和y是正整数”。典型的“快速”算法如下所示:

public long fastPower(int x, int y) {
  // Replaced my code with the "better" version described below,
  // but this version isn't measurably faster than what I had before
  long base = x; // otherwise, we may overflow at x *= x.
  long result = y % 2 == 1 ? x : 1;
  while (y > 1) {
    base *= base;
    y >>= 1;
    if (y % 2 == 1) result *= base;
  }

  return result;
}

我想看看这比调用 Math.pow() 或使用简单的方法(例如将 x 乘以 y 次)快多少,如下所示:

public long naivePower(int x, int y) {
  long result = 1;
  for (int i = 0; i < y; i++) {
    result *= x;
  }
  return result;
}

编辑:好的,有人(正确地)向我指出我的基准测试代码没有消耗结果,这完全让一切都失败了。一旦我开始使用结果,我仍然发现简单方法比“快速”方法快约 25%。

原文:

I was very surprised to find that the naive approach was 4x faster than the "fast" version, which was itself about 3x faster than the Math.pow() version.

我的测试使用 10,000,000 次试验(然后是 1 亿次,只是为了绝对确保 JIT 有时间预热),每个试验都使用随机值(以防止调用被优化掉)2

据我所知,对于小指数,天真的版本预计会更快。 “快速”版本有两个分支而不是一个,并且通常会执行两倍于天真的分支的算术/存储操作 - 但我预计对于大指数,这仍然会导致快速方法节省一半的操作最好的情况和最坏的情况大致相同。

任何人都知道为什么简单的方法会比“快速”版本快得多,即使数据偏向“快速”版本(即更大的指数)?该代码中的额外分支是否会在运行时造成如此大的差异?

基准测试代码(是的,我知道我应该使用一些框架来进行“官方”基准测试,但这是一个玩具问题)-更新以热身并使用结果:

PowerIf[] powers = new PowerIf[] {
  new EasyPower(), // just calls Math.pow() and cast to int
  new NaivePower(),
  new FastPower()
};

Random rand = new Random(0); // same seed for each run
int randCount = 10000;
int[] bases = new int[randCount];
int[] exponents = new int[randCount];
for (int i = 0; i < randCount; i++) {
  bases[i] = 2 + rand.nextInt(2);
  exponents[i] = 25 + rand.nextInt(5);
}

int count = 1000000000;

for (int trial = 0; trial < powers.length; trial++) {
  long total = 0;
  for (int i = 0; i < count; i++) { // warm up
    final int x = bases[i % randCount];
    final int y = exponents[i % randCount];
    total += powers[trial].power(x, y);
  }
  long start = System.currentTimeMillis();
  for (int i = 0; i < count; i++) {
    final int x = bases[i % randCount];
    final int y = exponents[i % randCount];
    total += powers[trial].power(x, y);
  }
  long end = System.currentTimeMillis();
  System.out.printf("%25s: %d ms%n", powers[trial].toString(), (end - start)); 
  System.out.println(total);
}

产生输出:



                EasyPower: 7908 ms
-407261252961037760
               NaivePower: 1993 ms
-407261252961037760
                FastPower: 2394 ms
-407261252961037760
  

使用随机数和试验的参数确实会改变输出特性,但测试之间的比率始终与所示的相同。


你的问题有两个fastPower:

  1. 最好更换y % 2 == 0 with (y & 1) == 0;按位运算速度更快。
  2. 你的代码总是递减y并执行额外的乘法,包括以下情况y甚至。最好将这部分放入else clause.

不管怎样,我猜你的基准测试方法并不完美。 4 倍的性能差异听起来很奇怪,在没有看到完整代码的情况下无法解释。

应用上述改进后,我已经验证使用JMH http://openjdk.java.net/projects/code-tools/jmh/基准测试fastPower确实比naivePower系数为 1.3 倍至 2 倍。

package bench;

import org.openjdk.jmh.annotations.*;

@State(Scope.Benchmark)
public class FastPow {
    @Param("3")
    int x;
    @Param({"25", "28", "31", "32"})
    int y;

    @Benchmark
    public long fast() {
        return fastPower(x, y);
    }

    @Benchmark
    public long naive() {
        return naivePower(x, y);
    }

    public static long fastPower(long x, int y) {
        long result = 1;
        while (y > 0) {
            if ((y & 1) == 0) {
                x *= x;
                y >>>= 1;
            } else {
                result *= x;
                y--;
            }
        }
        return result;
    }

    public static long naivePower(long x, int y) {
        long result = 1;
        for (int i = 0; i < y; i++) {
            result *= x;
        }
        return result;
    }
}

Results:

Benchmark      (x)  (y)   Mode  Cnt    Score   Error   Units
FastPow.fast     3   25  thrpt   10  103,406 ± 0,664  ops/us
FastPow.fast     3   28  thrpt   10  103,520 ± 0,351  ops/us
FastPow.fast     3   31  thrpt   10   85,390 ± 0,286  ops/us
FastPow.fast     3   32  thrpt   10  115,868 ± 0,294  ops/us
FastPow.naive    3   25  thrpt   10   76,331 ± 0,660  ops/us
FastPow.naive    3   28  thrpt   10   69,527 ± 0,464  ops/us
FastPow.naive    3   31  thrpt   10   54,407 ± 0,231  ops/us
FastPow.naive    3   32  thrpt   10   56,127 ± 0,207  ops/us

Note:整数乘法是相当快的运算,有时甚至比额外的比较更快 https://stackoverflow.com/questions/35531369/why-is-ab-0-faster-than-a-0-b-0-in-java。不要期望通过适合的值带来巨大的性能改进long。快速功率算法的优势将在BigInteger具有更大的指数。

Update

自从作者发布了基准测试以来,我必须承认令人惊讶的性能结果来自常见的基准测试陷阱。 我在保留原始方法的同时改进了基准测试,现在它表明FastPower确实比NaivePower, see here https://gist.github.com/apangin/91c07684635893e3f1d5.

改进版主要有哪些变化?

  1. 不同的算法应在不同的 JVM 实例中单独测试,以防止配置文件污染。
  2. 必须多次调用基准测试才能进行正确的编译/重新编译,直到达到稳定状态。
  3. 应将一个基准测试放在单独的方法中,以避免堆栈替换问题。
  4. y % 2被替换为y & 1因为 HotSpot 不会自动执行此优化。
  5. 最小化主基准测试循环中不相关操作的影响。

手动编写微基准是一项艰巨的任务。这就是为什么强烈建议使用适当的基准测试框架,例如JMH http://openjdk.java.net/projects/code-tools/jmh/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 中的“快速”整数幂 的相关文章

随机推荐