Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.stackoverflow;
- import org.openjdk.jmh.annotations.*;
- import org.openjdk.jmh.infra.Blackhole;
- import org.openjdk.jmh.runner.Runner;
- import org.openjdk.jmh.runner.RunnerException;
- import org.openjdk.jmh.runner.options.Options;
- import org.openjdk.jmh.runner.options.OptionsBuilder;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.util.Comparator;
- import java.util.PriorityQueue;
- import java.util.Random;
- @Warmup(iterations = 5)
- @Measurement(iterations = 2)
- @State(Scope.Benchmark)
- @Fork(1)
- @BenchmarkMode(Mode.Throughput)
- @Threads(1)
- public class CounterBenchmark {
- private static final int numberExamples = 10000;
- private static final int numberNeighbours = 10;
- private double sampleData[];
- @Setup
- public void init() throws IOException, IllegalAccessException, InstantiationException {
- Random rnd = new Random();
- sampleData = new double[numberExamples];
- for (int i = 0; i < numberExamples; i++) {
- sampleData[i] = rnd.nextDouble();
- }
- }
- @Benchmark
- public void testHeap(Blackhole bh) {
- final double[] scores = sampleData;
- PriorityQueue<Integer> myHeap = new PriorityQueue<>(numberNeighbours, new Comparator<Integer>() {
- @Override
- public int compare(Integer o1, Integer o2) {
- return -Double.compare(scores[o1], scores[o2]);
- }
- });
- int top;
- for (int i = 0; i < numberExamples; i++) {
- if (i < numberNeighbours) {
- myHeap.offer(i);
- } else {
- top = myHeap.peek();
- if (scores[top] > scores[i]) {
- myHeap.poll();
- myHeap.offer(i);
- }
- }
- }
- bh.consume(myHeap);
- }
- @Benchmark
- public void testSimple(Blackhole bh) {
- final double[] scores = sampleData;
- int[] candidates = new int[numberNeighbours];
- int top = 0;
- for (int i = 0; i < numberExamples; i++) {
- if (i < numberNeighbours) {
- candidates[i] = i;
- if (scores[candidates[top]] < scores[candidates[i]]) top = i;
- } else {
- if (scores[candidates[top]] > scores[i]) {
- candidates[top] = i;
- top = 0;
- for (int j = 1; j < numberNeighbours; j++) {
- if (scores[candidates[top]] < scores[candidates[j]]) top = j;
- }
- }
- }
- }
- bh.consume(candidates);
- }
- public static void main(String[] args) throws Exception {
- runTest();
- }
- private static void runTest() throws FileNotFoundException, RunnerException {
- Options opt = new OptionsBuilder()
- .include(".*" + CounterBenchmark.class.getSimpleName() + ".*")
- .forks(1)
- .build();
- new Runner(opt).run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement