Skip to content

Commit

Permalink
Add Helidon-Reactive Scrabble benchmark (#1482)
Browse files Browse the repository at this point in the history
* Add Helidon-Reactive Scrabble benchmark

* No need for pom changes
  • Loading branch information
akarnokd authored Mar 10, 2020
1 parent e49f648 commit 36ab8d4
Show file tree
Hide file tree
Showing 4 changed files with 108,830 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.common.reactive.jmh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

import org.openjdk.jmh.annotations.*;

/**
* Original copyright Jose Paumard, 2019.
* https://github.com/JosePaumard/jdk8-stream-rx-comparison-reloaded
*/
@State(Scope.Benchmark)
public class ShakespearePlaysScrabble {

public static final int[] letterScores = {
// a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10} ;

public static final int[] scrabbleAvailableLetters = {
// a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
9, 2, 2, 1, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1} ;

static class MutableLong {
long value;
long get() {
return value;
}

MutableLong set(long l) {
value = l;
return this;
}

MutableLong incAndSet() {
value++;
return this;
}

MutableLong add(MutableLong other) {
value += other.value;
return this;
}
}

public Set<String> scrabbleWords;
public Set<String> shakespeareWords;

@Setup
public void init() {
scrabbleWords = readScrabbleWords() ;
shakespeareWords = readShakespeareWords() ;
}


public static Set<String> readScrabbleWords() {
Set<String> scrabbleWords = new HashSet<>();

try (BufferedReader bin = new BufferedReader(new InputStreamReader(ShakespearePlaysScrabble.class.getResourceAsStream("/ospd.txt"), StandardCharsets.UTF_8))) {
String line = null;
while ((line = bin.readLine()) != null) {
scrabbleWords.add(line.toLowerCase());
}
} catch (IOException ex) {
ex.printStackTrace();
}

return scrabbleWords;
}

public static Set<String> readShakespeareWords() {
Set<String> shakespeareWords = new HashSet<>();

try (BufferedReader bin = new BufferedReader(new InputStreamReader(ShakespearePlaysScrabble.class.getResourceAsStream("/words.shakespeare.txt"), StandardCharsets.UTF_8))) {
String line = null;
while ((line = bin.readLine()) != null) {
shakespeareWords.add(line.toLowerCase());
}
} catch (IOException ex) {
ex.printStackTrace();
}

return shakespeareWords;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.common.reactive.jmh;

import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import io.helidon.common.mapper.Mapper;
import io.helidon.common.reactive.Multi;
import io.helidon.common.reactive.Single;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

/**
* Shakespeare plays Scrabble with Helidon Reactive.
* Based on the work of Jose Paumard (C) 2019
* https://github.com/JosePaumard/jdk8-stream-rx-comparison-reloaded
*/
public class ShakespearePlaysScrabbleWithHelidonReactiveOpt extends ShakespearePlaysScrabble {


public static void main(String[] args) throws Throwable {
ShakespearePlaysScrabbleWithHelidonReactiveOpt s = new ShakespearePlaysScrabbleWithHelidonReactiveOpt();
s.init();
System.out.println(s.measureThroughput());

Options opt = new OptionsBuilder()
.include(ShakespearePlaysScrabbleWithHelidonReactiveOpt.class.getSimpleName())
.forks(1)
.warmupIterations(5)
.warmupTime(TimeValue.seconds(1))
.measurementIterations(5)
.measurementTime(TimeValue.seconds(1))
.timeUnit(TimeUnit.MILLISECONDS)
.mode(Mode.SampleTime)
.build();

new Runner(opt).run();
}

static Multi<Integer> chars(String s) {
return Multi.range(0, s.length()).map(idx -> (int)s.charAt(idx));
}

static <T> T get(Single<T> source) {
try {
return source.get();
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}

@SuppressWarnings("unused")
@Benchmark
public List<Entry<Integer, List<String>>> measureThroughput() throws Exception {

// to compute the score of a given word
Mapper<Integer, Integer> scoreOfALetter = letter -> letterScores[letter - 'a'];

// score of the same letters in a word
Mapper<Entry<Integer, MutableLong>, Integer> letterScore =
entry ->
letterScores[entry.getKey() - 'a'] *
Integer.min(
(int)entry.getValue().get(),
scrabbleAvailableLetters[entry.getKey() - 'a']
)
;


Function<String, Multi<Integer>> toIntegerFlowable =
ShakespearePlaysScrabbleWithHelidonReactiveOpt::chars;

// Histogram of the letters in a given word
Function<String, Single<HashMap<Integer, MutableLong>>> histoOfLetters =
word -> toIntegerFlowable.apply(word)
.collect(
HashMap::new,
(HashMap<Integer, MutableLong> map, Integer value) ->
{
MutableLong newValue = map.get(value) ;
if (newValue == null) {
newValue = new MutableLong();
map.put(value, newValue);
}
newValue.incAndSet();
}

) ;

// number of blanks for a given letter
Mapper<Entry<Integer, MutableLong>, Long> blank =
entry ->
Long.max(
0L,
entry.getValue().get() -
scrabbleAvailableLetters[entry.getKey() - 'a']
)
;

// number of blanks for a given word
Function<String, Single<Long>> nBlanks =
word ->
Multi.from(histoOfLetters.apply(word))
.flatMapIterable(HashMap::entrySet)
.map(blank)
.collectStream(Collectors.summarizingLong(value -> value))
.map(LongSummaryStatistics::getSum)
;


// can a word be written with 2 blanks?
Function<String, Single<Boolean>> checkBlanks =
word -> nBlanks.apply(word)
.map(l -> l <= 2L) ;

// score taking blanks into account letterScore1
Function<String, Single<Integer>> score2 =
word ->
Multi.from(histoOfLetters.apply(word))
.flatMapIterable(
HashMap::entrySet
)
.map(letterScore)
.collectStream(Collectors.summarizingInt(value -> value))
.map(v -> (int)v.getSum())
;

// Placing the word on the board
// Building the streams of first and last letters
Function<String, Multi<Integer>> first3 =
word -> chars(word).limit(3) ;
Function<String, Multi<Integer>> last3 =
word -> chars(word).skip(3) ;


// Stream to be maxed
Function<String, Multi<Integer>> toBeMaxed =
word -> Multi.concat(first3.apply(word), last3.apply(word))
;

// Bonus for double letter
Function<String, Single<Integer>> bonusForDoubleLetter =
word -> toBeMaxed.apply(word)
.map(scoreOfALetter)
.collectStream(Collectors.summarizingInt(value -> value))
.map(v -> (int)v.getMax())
;

// score of the word put on the board
Function<String, Single<Integer>> score3 =
word ->
Multi.concat(
Multi.from(score2.apply(word)),
Multi.from(bonusForDoubleLetter.apply(word))
)
.collectStream(Collectors.summarizingInt(value -> value))
.map(w -> {
int v = (int) w.getSum();
return v * 2 + (word.length() == 7 ? 50 : 0);
})
;

Function<Function<String, Single<Integer>>, Single<TreeMap<Integer, List<String>>>> buildHistoOnScore =
score -> Multi.from(shakespeareWords)
.filter(scrabbleWords::contains)
.filter(word -> get(checkBlanks.apply(word)))
.collect(
() -> new TreeMap<Integer, List<String>>(Comparator.reverseOrder()),
(TreeMap<Integer, List<String>> map, String word) -> {
Integer key = get(score.apply(word)) ;
List<String> list = map.get(key) ;
if (list == null) {
list = new ArrayList<>() ;
map.put(key, list) ;
}
list.add(word) ;
}
) ;

// best key / value pairs
List<Entry<Integer, List<String>>> finalList2 =
Multi.from(buildHistoOnScore.apply(score3))
.flatMapIterable(
TreeMap::entrySet
)
.limit(3)
.collect(
(Supplier<ArrayList<Entry<Integer, List<String>>>>) ArrayList::new,
ArrayList::add
)
.get() ;


// System.out.println(finalList2);

return finalList2 ;
}
}
Loading

0 comments on commit 36ab8d4

Please sign in to comment.