Skip to content

Instantly share code, notes, and snippets.

@manuelbernhardt
Created July 20, 2016 07:02
Show Gist options
  • Save manuelbernhardt/718ba5c7c3ec06d73eaf6f8a6fe88b70 to your computer and use it in GitHub Desktop.
Save manuelbernhardt/718ba5c7c3ec06d73eaf6f8a6fe88b70 to your computer and use it in GitHub Desktop.
Calculates PI to keep CPU busy
package com.typesafe.training.coffeehouse;
import scala.concurrent.duration.Duration;
import java.math.BigDecimal;
public class Busy {
public static BigDecimal busy(Duration duration) {
return pi(System.nanoTime() + duration.toNanos());
}
private static BigDecimal gregoryLeibnitz(int n) {
return new BigDecimal(4.0 * (1 - (n % 2) * 2) / (n * 2 + 1));
}
private static BigDecimal pi(Long endNanos) {
int n = 0;
BigDecimal acc = new BigDecimal(0.0);
while (System.nanoTime() < endNanos) {
acc.add(gregoryLeibnitz(n));
n++;
}
return acc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment