这个斐波那契数列让我的所有 4 个核心都接近 100%:
public static BigInteger fib(BigInteger n) {
if (n.compareTo(BigInteger.ONE) == -1 || n.compareTo(BigInteger.ONE) == 0 ) return n;
else
return fib(n.subtract(BigInteger.ONE)).add(fib(n.subtract(BigInteger.ONE).subtract(BigInteger.ONE)));
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int j = 0; j < 10; j++) {
final int ID = j;
executorService.submit(new Runnable() {
public void run() {
for (int i=0;i < Integer.MAX_VALUE; i++) {
System.out.println(ID+" worker: "+i + ": " + fib(new BigInteger(String.valueOf(i))));
}
}
});
}
}
这很可能不足以进行基准测试:
但是写了15分钟,而且是CPU密集型的。关于现实生活中的例子,请阅读 HotLicks 评论。因此,如果您想要密码破解器,这里是查找素数的最低效方法,这是破解 RSA的基本操作:
public static boolean isPrime(BigInteger n) {
BigInteger counter = BigInteger.ONE.add(BigInteger.ONE);
boolean isPrime = true;
while (counter.compareTo(n) == -1) {
if (n.remainder(counter).compareTo(BigInteger.ZERO) == 0) {
isPrime = false;
break;
}
counter = counter.add(BigInteger.ONE);
}
return isPrime;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int j = 0; j < 10; j++) {
final int ID = j;
executorService.submit(new Runnable() {
public void run() {
BigInteger number = BigInteger.ONE;
while(true) {
System.out.println(ID+" worker: "+number + ": " + isPrime(number));
number = number.add(BigInteger.ONE);
}
}
});
}
}
它比 Fibonnaci 占用更少的 CPU:
可能是因为斐波那契有递归调用。
链接的答案是已知 CPU 密集型问题的列表。它甚至提到了RSA 挑战。