Skip to content

Instantly share code, notes, and snippets.

@amaembo
Created May 3, 2016 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amaembo/6487c3484843a26a7848f761fd43d511 to your computer and use it in GitHub Desktop.
Save amaembo/6487c3484843a26a7848f761fd43d511 to your computer and use it in GitHub Desktop.
import java.util.concurrent.*;
import java.util.stream.*;
import java.util.function.*;
import java.util.*;
import one.util.streamex.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.annotations.*;
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(3)
@State(Scope.Benchmark)
public class SumNegSubarrays {
@Param({"20", "200", "2000"})
int n;
int[] a;
@Setup(Level.Iteration)
public void setup() {
a = new int[n];
for (int i = 0; i < n; i ++)
a[i] = ThreadLocalRandom.current().nextInt(-20, 21);
}
@Benchmark
public long plain() {
long global = 0;
for (int i = 0; i < a.length; i++) {
long sum = 0, negs = 0;
for (int j = i; j < a.length; j++) {
sum += a[j];
if (sum < 0)
negs += 1;
}
global += negs;
}
return global;
}
@Benchmark
public long stream() {
return IntStream.range(0, a.length)
.flatMap(from -> IntStream.rangeClosed(from + 1, a.length)
.map(to -> Arrays.stream(a, from, to).sum()))
.filter(sum -> sum < 0)
.count();
}
@Benchmark
public long streamEx() {
return IntStreamEx.range(a.length)
.mapToObj(from -> IntStreamEx.of(a, from, a.length).scanLeft(Integer::sum))
.flatMapToInt(IntStreamEx::of)
.less(0)
.count();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment