Created
July 20, 2016 07:02
-
-
Save manuelbernhardt/718ba5c7c3ec06d73eaf6f8a6fe88b70 to your computer and use it in GitHub Desktop.
Calculates PI to keep CPU busy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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