Skip to content

Commit

Permalink
Merge pull request #22 from Netflix/feature/fast_sqrt
Browse files Browse the repository at this point in the history
Optimized function for calculating square roots
  • Loading branch information
elandau authored Feb 13, 2018
2 parents 72fe8b6 + 7c8ee97 commit 5c2e480
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.netflix.concurrency.limits.limit.functions;

import java.util.function.Function;
import java.util.stream.IntStream;

/**
* Specialized utility function used by limiters to calculate thredsholds using square root
* of the current limit. Here we pre-compute the square root of numbers up to 1000 because
* the square root operation can be slow.
*/
public final class SquareRootFunction implements Function<Integer, Integer> {
static final int[] lookup = new int[1000];

static {
IntStream.range(0, 1000).forEach(i -> lookup[i] = (int)Math.sqrt(i));
}

private static final SquareRootFunction INSTANCE = new SquareRootFunction();

/**
* Create an instance of a function that returns : baseline + sqrt(limit)
*
* @param baseline
* @return
*/
public static Function<Integer, Integer> create(int baseline) {
return INSTANCE.andThen(t -> t + baseline);
}

@Override
public Integer apply(Integer t) {
return t < 1000 ? lookup[t] : (int)Math.sqrt(t);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.netflix.concurrency.limits.limit.functions;

import java.util.function.Function;

import org.junit.Assert;
import org.junit.Test;

public class SquareRootFunctionTest {
@Test
public void confirm0Index() {
Function<Integer, Integer> func = SquareRootFunction.create(4);
Assert.assertEquals(4, func.apply(0).intValue());
}

@Test
public void confirmMaxIndex() {
Function<Integer, Integer> func = SquareRootFunction.create(4);
Assert.assertEquals(35, func.apply(999).intValue());
}

@Test
public void confirmOutofLookupRange() {
Function<Integer, Integer> func = SquareRootFunction.create(4);
Assert.assertEquals(35, func.apply(1005).intValue());
}
}

0 comments on commit 5c2e480

Please sign in to comment.