diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml new file mode 100644 index 0000000..b7fccac --- /dev/null +++ b/.github/workflows/codspeed.yml @@ -0,0 +1,51 @@ +name: CodSpeed Benchmarks + +on: + push: + branches: [main, master] + pull_request: + # `workflow_dispatch` allows CodSpeed to trigger backtest + # performance analysis in order to generate initial data. + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read # required for actions/checkout + id-token: write # required for OIDC authentication with CodSpeed + +jobs: + benchmarks: + name: Run benchmarks + # CodSpeed macro runners give much more stable walltime measurements. + # Switch to `runs-on: codspeed-macro` once they are enabled for this + # organization: https://codspeed.io/docs/features/macro-runners + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + # Only fetch the CodSpeed JMH fork and its native hooks, not the + # example submodules bundled with codspeed-jvm. + - name: Fetch the CodSpeed JMH fork + run: | + git submodule update --init third-party/codspeed-jvm + git -C third-party/codspeed-jvm submodule update --init \ + jmh-fork/jmh-core/native-instrument-hooks/instrument-hooks + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "21" + + - name: Build the benchmark jar + working-directory: bench + run: ./gradlew --no-daemon jmhJar + + - name: Run the benchmarks + uses: CodSpeedHQ/action@v5 + with: + mode: walltime + run: java -jar bench/build/libs/clojure-algorithms-bench-jmh.jar -gc true diff --git a/.gitignore b/.gitignore index 0ecb091..4842ed6 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,7 @@ *.class /out/ node_modules/ -.DS_Store \ No newline at end of file +.DS_Store +.gradle/ +/bench/build/ +!/bench/gradle/wrapper/gradle-wrapper.jar diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..1b36804 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "third-party/codspeed-jvm"] + path = third-party/codspeed-jvm + url = https://github.com/CodSpeedHQ/codspeed-jvm.git diff --git a/README.md b/README.md index f8d681b..f01801e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Clojure Algorithms +[![CodSpeed](https://img.shields.io/endpoint?url=https://codspeed.io/badge.json)](https://app.codspeed.io/hhh-pa/clojure-algorithms?utm_source=badge) + A Clojure port of [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) — classic algorithms and data structures implemented in idiomatic Clojure. @@ -52,6 +54,29 @@ clojure -M:cljfmt clojure -T:build jar ``` +## Benchmarks + +Performance is tracked continuously with [CodSpeed](https://codspeed.io) +using [JMH](https://github.com/openjdk/jmh) through the CodSpeed JMH fork +(`third-party/codspeed-jvm`, a git submodule). The benchmarks live in +`bench/`: Java JMH classes in `bench/src/jmh/java` call the Clojure +functions directly, with deterministic inputs built in +`bench/src/jmh/clojure/clojure_algorithms/bench/fixtures.clj`. + +```bash +# Fetch the CodSpeed JMH fork +git submodule update --init third-party/codspeed-jvm +git -C third-party/codspeed-jvm submodule update --init \ + jmh-fork/jmh-core/native-instrument-hooks/instrument-hooks + +# Run all benchmarks (or a subset with -Pbench=, e.g. -Pbench=Sorts) +(cd bench && ./gradlew jmh) + +# Run them with the CodSpeed runner +(cd bench && ./gradlew jmhJar) +codspeed run --mode walltime -- java -jar bench/build/libs/clojure-algorithms-bench-jmh.jar +``` + ## Structure ``` diff --git a/bench/build.gradle.kts b/bench/build.gradle.kts new file mode 100644 index 0000000..e36bb33 --- /dev/null +++ b/bench/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + java + id("me.champeau.jmh") version "0.7.3" +} + +repositories { + mavenCentral() +} + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +sourceSets { + named("jmh") { + // Clojure sources are loaded (and compiled) at runtime from the + // classpath, so the library and the benchmark fixtures are shipped as + // resources of the benchmark jar. + resources { + srcDir("../src") + srcDir("../resources") + srcDir("src/jmh/clojure") + } + } +} + +dependencies { + // Keep in sync with deps.edn + jmh("org.clojure:clojure:1.12.0") +} + +jmh { + // Resolved to the CodSpeed JMH fork through the composite build in + // settings.gradle.kts. + jmhVersion.set("0.2.1") + + // Warmup/measurement/fork settings are declared with annotations on the + // benchmark classes so they also apply when running the jar directly. + forceGC.set(true) + + // Optional benchmark filter, e.g. `./gradlew jmh -Pbench=Sorts` + project.findProperty("bench")?.let { includes.set(listOf(it.toString())) } +} diff --git a/bench/gradle/wrapper/gradle-wrapper.jar b/bench/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..8bdaf60 Binary files /dev/null and b/bench/gradle/wrapper/gradle-wrapper.jar differ diff --git a/bench/gradle/wrapper/gradle-wrapper.properties b/bench/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2a84e18 --- /dev/null +++ b/bench/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/bench/gradlew b/bench/gradlew new file mode 100755 index 0000000..ef07e01 --- /dev/null +++ b/bench/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# 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 +# +# https://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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/bench/gradlew.bat b/bench/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/bench/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/bench/settings.gradle.kts b/bench/settings.gradle.kts new file mode 100644 index 0000000..6c19beb --- /dev/null +++ b/bench/settings.gradle.kts @@ -0,0 +1,13 @@ +rootProject.name = "clojure-algorithms-bench" + +// Use the CodSpeed fork of JMH (git submodule) in place of upstream JMH so +// benchmark results are collected and reported to CodSpeed. +includeBuild("../third-party/codspeed-jvm/jmh-fork") { + dependencySubstitution { + substitute(module("org.openjdk.jmh:jmh-core")).using(project(":jmh-core")) + substitute(module("org.openjdk.jmh:jmh-generator-annprocess")).using(project(":jmh-generator-annprocess")) + substitute(module("org.openjdk.jmh:jmh-generator-bytecode")).using(project(":jmh-generator-bytecode")) + substitute(module("org.openjdk.jmh:jmh-generator-reflection")).using(project(":jmh-generator-reflection")) + substitute(module("org.openjdk.jmh:jmh-generator-asm")).using(project(":jmh-generator-asm")) + } +} diff --git a/bench/src/jmh/clojure/clojure_algorithms/bench/fixtures.clj b/bench/src/jmh/clojure/clojure_algorithms/bench/fixtures.clj new file mode 100644 index 0000000..9aed321 --- /dev/null +++ b/bench/src/jmh/clojure/clojure_algorithms/bench/fixtures.clj @@ -0,0 +1,114 @@ +(ns clojure-algorithms.bench.fixtures + "Deterministic inputs for the JMH benchmarks in bench/src/jmh/java. + Every generator uses a fixed seed so runs are comparable over time." + (:import (java.util Random))) + +(defn random-ints + "Vector of `n` pseudo-random longs in [0, bound), seeded with `seed`." + ([n] (random-ints n 1000000 42)) + ([n bound seed] + (let [rng (Random. seed)] + (vec (repeatedly n #(long (.nextInt rng (int bound)))))))) + +(defn sorted-ints + "Sorted vector of `n` distinct longs (0, 2, 4, ...)." + [n] + (vec (range 0 (* 2 n) 2))) + +(defn random-text + "Pseudo-random lowercase string of length `n` over the first `alphabet` + letters, seeded with `seed`." + ([n] (random-text n 26 7)) + ([n alphabet seed] + (let [rng (Random. seed) + sb (StringBuilder. (int n))] + (dotimes [_ n] + (.append sb (char (+ 97 (.nextInt rng (int alphabet)))))) + (str sb)))) + +(def ^:private lorem + (str "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " + "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim " + "ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " + "aliquip ex ea commodo consequat. ")) + +(defn prose + "English-like text of at least `n` characters, truncated to `n`." + [n] + (let [s (apply str (repeat (inc (quot n (count lorem))) lorem))] + (subs s 0 n))) + +(defn weighted-digraph + "String-keyed adjacency map {node [[neighbour cost] ...]} with `n` nodes + and `degree` random outgoing edges per node, plus a chain n0 -> n1 -> ... + so every node is reachable from \"n0\"." + [n degree seed] + (let [rng (Random. seed) + node (fn [i] (str "n" i))] + (into {} + (for [i (range n)] + [(node i) + (vec (concat + (when (< (inc i) n) [[(node (inc i)) 10]]) + (repeatedly degree + (fn [] [(node (.nextInt rng (int n))) + (inc (.nextInt rng 9))]))))])))) + +(defn weighted-edges + "Vector of `m` random [u v weight] edges over `n` nodes, plus a chain so + the graph is connected." + [n m seed] + (let [rng (Random. seed)] + (vec (concat + (for [i (range (dec n))] [i (inc i) 1000]) + (repeatedly m (fn [] [(.nextInt rng (int n)) + (.nextInt rng (int n)) + (inc (.nextInt rng 999))])))))) + +(defn random-edges + "Vector of `m` random directed [u v] edges over `n` nodes." + [n m seed] + (let [rng (Random. seed)] + (vec (repeatedly m (fn [] [(.nextInt rng (int n)) (.nextInt rng (int n))]))))) + +(defn bfs-graph + "Directed graph {vertex #{neighbours}} with `n` vertices and `degree` + random edges per vertex, plus a chain for reachability." + [n degree seed] + (let [rng (Random. seed)] + (into {} + (for [i (range n)] + [i (into (if (< (inc i) n) #{(inc i)} #{}) + (repeatedly degree #(.nextInt rng (int n))))])))) + +(defn random-signed-ints + "Vector of `n` pseudo-random longs in (-bound, bound), seeded with `seed`." + [n bound seed] + (let [rng (Random. seed)] + (vec (repeatedly n #(long (- (.nextInt rng (int (* 2 bound))) bound)))))) + +(defn inc-all + "Increments every element of `coll`; returns a vector." + [coll] + (mapv inc coll)) + +(defn adjacency-map + "Directed graph {u [v ...]} over `n` nodes from `m` random edges." + [n m seed] + (reduce (fn [g [u v]] (update g u conj v)) + (into {} (map #(vector % []) (range n))) + (random-edges n m seed))) + +(defn binary-grid + "`size` x `size` grid of 1 (walkable) / 0 (obstacle) cells with roughly + `obstacle-pct` percent obstacles. Corners are always walkable." + [size obstacle-pct seed] + (let [rng (Random. seed) + last-cell (dec size)] + (vec (for [r (range size)] + (vec (for [c (range size)] + (if (or (and (zero? r) (zero? c)) + (and (= r last-cell) (= c last-cell)) + (>= (.nextInt rng 100) obstacle-pct)) + 1 + 0))))))) diff --git a/bench/src/jmh/java/clojure_algorithms/bench/Clj.java b/bench/src/jmh/java/clojure_algorithms/bench/Clj.java new file mode 100644 index 0000000..7b2bcc6 --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/Clj.java @@ -0,0 +1,26 @@ +package clojure_algorithms.bench; + +import clojure.java.api.Clojure; +import clojure.lang.IFn; + +/** Small helpers to load Clojure namespaces and resolve their functions from JMH benchmarks. */ +final class Clj { + private static final IFn REQUIRE = Clojure.var("clojure.core", "require"); + private static final String PREFIX = "clojure-algorithms."; + + private Clj() {} + + /** + * Requires {@code clojure-algorithms.} and returns the function {@code name} defined in it. + */ + static IFn fn(String ns, String name) { + String fullNs = PREFIX + ns; + REQUIRE.invoke(Clojure.read(fullNs)); + return Clojure.var(fullNs, name); + } + + /** Returns a function from the benchmark fixtures namespace. */ + static IFn fixture(String name) { + return fn("bench.fixtures", name); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/DataCompressionBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/DataCompressionBenchmark.java new file mode 100644 index 0000000..a8a17ad --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/DataCompressionBenchmark.java @@ -0,0 +1,70 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class DataCompressionBenchmark { + private IFn huffmanEncode; + private IFn lz77Compress; + private IFn bwtTransform; + private IFn runLengthEncode; + private IFn lzwCompress; + + private Object lz77Compressor; + private String prose4k; + private String prose1k; + private String prose500; + private String binaryRuns4k; + private String bits4k; + + @Setup(Level.Trial) + public void setup() { + huffmanEncode = Clj.fn("data-compression.huffman", "encode-text"); + lz77Compress = Clj.fn("data-compression.lz77", "compress"); + bwtTransform = Clj.fn("data-compression.burrows-wheeler", "bwt-transform"); + runLengthEncode = Clj.fn("data-compression.run-length-encoding", "run-length-encode"); + lzwCompress = Clj.fn("data-compression.lempel-ziv", "compress-data"); + + lz77Compressor = Clj.fn("data-compression.lz77", "make-compressor").invoke(); + + IFn prose = Clj.fixture("prose"); + IFn randomText = Clj.fixture("random-text"); + prose4k = (String) prose.invoke(4096); + prose1k = (String) prose.invoke(1000); + prose500 = (String) prose.invoke(500); + binaryRuns4k = (String) randomText.invoke(4096, 2, 3L); + // "a"/"b" -> "0"/"1" bit string for the LZW compressor. + bits4k = binaryRuns4k.replace('a', '0').replace('b', '1'); + } + + @Benchmark + public Object huffmanEncode4k() { + return huffmanEncode.invoke(prose4k); + } + + @Benchmark + public Object lz77Compress1k() { + return lz77Compress.invoke(lz77Compressor, prose1k); + } + + @Benchmark + public Object burrowsWheelerTransform500() { + return bwtTransform.invoke(prose500); + } + + @Benchmark + public Object runLengthEncode4k() { + return runLengthEncode.invoke(binaryRuns4k); + } + + @Benchmark + public Object lempelZivCompress4k() { + return lzwCompress.invoke(bits4k); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/DynamicProgrammingBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/DynamicProgrammingBenchmark.java new file mode 100644 index 0000000..107cc95 --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/DynamicProgrammingBenchmark.java @@ -0,0 +1,103 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class DynamicProgrammingBenchmark { + private IFn lcs; + private IFn editDistance; + private IFn knapsack; + private IFn lisLength; + private IFn matrixChainOrder; + private IFn maxSubarraySum; + private IFn floydWarshall; + + private String wordA150; + private String wordB150; + private String wordA300; + private String wordB300; + private Object knapsackWeights; + private Object knapsackValues; + private Object random10k; + private Object signed10k; + private Object matrixDims; + private Object fwGraph; + + @Setup(Level.Trial) + public void setup() { + lcs = Clj.fn("dynamic-programming.longest-common-subsequence", "longest-common-subsequence"); + editDistance = Clj.fn("dynamic-programming.edit-distance", "min-dist-bottom-up"); + knapsack = Clj.fn("dynamic-programming.knapsack", "knapsack"); + lisLength = + Clj.fn( + "dynamic-programming.longest-increasing-subsequence-o-nlogn", + "longest-increasing-subsequence-length"); + matrixChainOrder = Clj.fn("dynamic-programming.matrix-chain-order", "matrix-chain-order"); + maxSubarraySum = Clj.fn("dynamic-programming.max-subarray-sum", "max-subarray-sum"); + floydWarshall = Clj.fn("dynamic-programming.floyd-warshall", "floyd-warshall"); + + IFn randomText = Clj.fixture("random-text"); + IFn randomInts = Clj.fixture("random-ints"); + wordA150 = (String) randomText.invoke(150, 26, 1L); + wordB150 = (String) randomText.invoke(150, 26, 2L); + wordA300 = (String) randomText.invoke(300, 26, 1L); + wordB300 = (String) randomText.invoke(300, 26, 2L); + // Weights in [1, 50], values in [0, 100). + knapsackWeights = Clj.fixture("inc-all").invoke(randomInts.invoke(100, 50, 5L)); + knapsackValues = randomInts.invoke(100, 100, 6L); + random10k = randomInts.invoke(10000); + signed10k = Clj.fixture("random-signed-ints").invoke(10000, 1000, 8L); + matrixDims = Clj.fixture("inc-all").invoke(randomInts.invoke(60, 100, 10L)); + + IFn makeGraph = Clj.fn("dynamic-programming.floyd-warshall", "make-graph"); + IFn addEdge = Clj.fn("dynamic-programming.floyd-warshall", "add-edge"); + Object graph = makeGraph.invoke(60); + for (Object e : (List) Clj.fixture("weighted-edges").invoke(60, 400, 15L)) { + List edge = (List) e; + graph = addEdge.invoke(graph, edge.get(0), edge.get(1), edge.get(2)); + } + fwGraph = graph; + } + + @Benchmark + public Object longestCommonSubsequence150() { + return lcs.invoke(wordA150, wordB150); + } + + @Benchmark + public Object editDistance300() { + return editDistance.invoke(wordA300, wordB300); + } + + @Benchmark + public Object knapsack100Items() { + return knapsack.invoke(500L, knapsackWeights, knapsackValues, 100L); + } + + @Benchmark + public Object longestIncreasingSubsequence10k() { + return lisLength.invoke(random10k); + } + + @Benchmark + public Object matrixChainOrder60() { + return matrixChainOrder.invoke(matrixDims); + } + + @Benchmark + public Object maxSubarraySum10k() { + return maxSubarraySum.invoke(signed10k); + } + + @Benchmark + public Object floydWarshall60() { + return floydWarshall.invoke(fwGraph); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/GraphsBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/GraphsBenchmark.java new file mode 100644 index 0000000..519396c --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/GraphsBenchmark.java @@ -0,0 +1,80 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import clojure.lang.PersistentVector; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class GraphsBenchmark { + private IFn dijkstra; + private IFn dijkstraGrid; + private IFn bfs; + private IFn kruskal; + private IFn tarjan; + private IFn kosaraju; + + private Object weightedDigraph; + private Object bfsGraph; + private Object weightedEdges; + private Object adjacencyVector; + private Object adjacencyMap; + private Object grid; + private Object gridSource; + private Object gridTarget; + + @Setup(Level.Trial) + public void setup() { + dijkstra = Clj.fn("graphs.dijkstra", "dijkstra"); + dijkstraGrid = Clj.fn("graphs.dijkstra-binary-grid", "dijkstra"); + bfs = Clj.fn("graphs.breadth-first-search", "bfs"); + kruskal = Clj.fn("graphs.minimum-spanning-tree-kruskal", "kruskal"); + tarjan = Clj.fn("graphs.tarjans-scc", "tarjan"); + kosaraju = Clj.fn("graphs.scc-kosaraju", "kosaraju"); + + weightedDigraph = Clj.fixture("weighted-digraph").invoke(2000, 4, 11L); + bfsGraph = Clj.fixture("bfs-graph").invoke(5000, 4, 12L); + weightedEdges = Clj.fixture("weighted-edges").invoke(2000, 8000, 13L); + adjacencyVector = + Clj.fn("graphs.tarjans-scc", "create-graph") + .invoke(2000, Clj.fixture("random-edges").invoke(2000, 4000, 14L)); + adjacencyMap = Clj.fixture("adjacency-map").invoke(2000, 4000, 14L); + grid = Clj.fixture("binary-grid").invoke(40, 20, 16L); + gridSource = PersistentVector.create(0L, 0L); + gridTarget = PersistentVector.create(39L, 39L); + } + + @Benchmark + public Object dijkstra2000Nodes() { + return dijkstra.invoke(weightedDigraph, "n0", "n1999"); + } + + @Benchmark + public Object dijkstraBinaryGrid40x40() { + return dijkstraGrid.invoke(grid, gridSource, gridTarget, Boolean.TRUE); + } + + @Benchmark + public Object breadthFirstSearch5000Nodes() { + return bfs.invoke(bfsGraph, 0L); + } + + @Benchmark + public Object kruskalMst2000Nodes() { + return kruskal.invoke(2000L, weightedEdges); + } + + @Benchmark + public Object tarjanScc2000Nodes() { + return tarjan.invoke(adjacencyVector); + } + + @Benchmark + public Object kosarajuScc2000Nodes() { + return kosaraju.invoke(adjacencyMap, 2000L); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/HashesBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/HashesBenchmark.java new file mode 100644 index 0000000..6054f72 --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/HashesBenchmark.java @@ -0,0 +1,66 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class HashesBenchmark { + private IFn sha256; + private IFn sha1; + private IFn md5; + private IFn crc32; + private IFn adler32; + private IFn djb2; + + private String text1k; + private String text4k; + + @Setup(Level.Trial) + public void setup() { + sha256 = Clj.fn("hashes.sha256", "sha256"); + sha1 = Clj.fn("hashes.sha1", "sha1"); + md5 = Clj.fn("hashes.md5", "md5"); + crc32 = Clj.fn("hashes.crc32", "crc32-str"); + adler32 = Clj.fn("hashes.adler32", "adler32"); + djb2 = Clj.fn("hashes.djb2", "djb2"); + + IFn prose = Clj.fixture("prose"); + text1k = (String) prose.invoke(1024); + text4k = (String) prose.invoke(4096); + } + + @Benchmark + public Object sha256_1k() { + return sha256.invoke(text1k); + } + + @Benchmark + public Object sha1_4k() { + return sha1.invoke(text4k); + } + + @Benchmark + public Object md5_4k() { + return md5.invoke(text4k); + } + + @Benchmark + public Object crc32_4k() { + return crc32.invoke(text4k); + } + + @Benchmark + public Object adler32_4k() { + return adler32.invoke(text4k); + } + + @Benchmark + public Object djb2_4k() { + return djb2.invoke(text4k); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/MathsBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/MathsBenchmark.java new file mode 100644 index 0000000..fc9d0dc --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/MathsBenchmark.java @@ -0,0 +1,82 @@ +package clojure_algorithms.bench; + +import clojure.lang.BigInt; +import clojure.lang.IFn; +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class MathsBenchmark { + private IFn sieveOfEratosthenes; + private IFn sieveOfAtkin; + private IFn segmentedSieve; + private IFn isPrime; + private IFn primeFactors; + private IFn totient; + private IFn fibIterative; + private IFn karatsuba; + + private Object bigA; + private Object bigB; + + @Setup(Level.Trial) + public void setup() { + sieveOfEratosthenes = Clj.fn("maths.sieve-of-eratosthenes", "prime-sieve"); + sieveOfAtkin = Clj.fn("maths.sieve-of-atkin", "sieve-of-atkin"); + segmentedSieve = Clj.fn("maths.segmented-sieve", "sieve"); + isPrime = Clj.fn("maths.prime-check", "is-prime"); + primeFactors = Clj.fn("maths.prime-factors", "prime-factors"); + totient = Clj.fn("maths.eulers-totient", "totient"); + fibIterative = Clj.fn("maths.fibonacci", "fib-iterative"); + karatsuba = Clj.fn("maths.karatsuba", "karatsuba"); + + bigA = BigInt.fromBigInteger(new BigInteger("31415926535897932384626433832795028841")); + bigB = BigInt.fromBigInteger(new BigInteger("27182818284590452353602874713526624977")); + } + + @Benchmark + public Object sieveOfEratosthenes100k() { + return sieveOfEratosthenes.invoke(100000L); + } + + @Benchmark + public Object sieveOfAtkin100k() { + return sieveOfAtkin.invoke(100000L); + } + + @Benchmark + public Object segmentedSieve100k() { + return segmentedSieve.invoke(100000L); + } + + @Benchmark + public Object isPrimeLargePrime() { + return isPrime.invoke(1000000007L); + } + + @Benchmark + public Object primeFactorsSemiprime() { + // 999983 * 1000003 + return primeFactors.invoke(999985999949L); + } + + @Benchmark + public Object eulersTotient100k() { + return totient.invoke(100000L); + } + + @Benchmark + public Object fibonacciIterative1000() { + return fibIterative.invoke(1000L); + } + + @Benchmark + public Object karatsuba38Digits() { + return karatsuba.invoke(bigA, bigB); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/SearchesBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/SearchesBenchmark.java new file mode 100644 index 0000000..e49b53b --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/SearchesBenchmark.java @@ -0,0 +1,52 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class SearchesBenchmark { + private IFn binarySearch; + private IFn bisectLeft; + private IFn quickSelect; + private IFn linearSearch; + + private Object sorted10k; + private Object random10k; + + @Setup(Level.Trial) + public void setup() { + binarySearch = Clj.fn("searches.binary-search", "binary-search"); + bisectLeft = Clj.fn("searches.binary-search", "bisect-left"); + quickSelect = Clj.fn("searches.quick-select", "quick-select"); + linearSearch = Clj.fn("searches.linear-search", "linear-search"); + + sorted10k = Clj.fixture("sorted-ints").invoke(10000); + random10k = Clj.fixture("random-ints").invoke(10000); + } + + @Benchmark + public Object binarySearch10k() { + return binarySearch.invoke(sorted10k, 13370L); + } + + @Benchmark + public Object bisectLeft10k() { + return bisectLeft.invoke(sorted10k, 13371L); + } + + @Benchmark + public Object linearSearch10k() { + return linearSearch.invoke(sorted10k, 19998L); + } + + @Benchmark + public Object quickSelectMedian10k() { + // Fixed seed so the pivot sequence (and the work done) is identical every call. + return quickSelect.invoke(random10k, 5000L, 1234L); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/SortsBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/SortsBenchmark.java new file mode 100644 index 0000000..e1b827a --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/SortsBenchmark.java @@ -0,0 +1,78 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class SortsBenchmark { + private IFn mergeSort; + private IFn quickSort; + private IFn heapSort; + private IFn timSort; + private IFn insertionSort; + private IFn shellSort; + private IFn countingSort; + + private Object random5k; + private Object smallRange5k; + private Object random2k; + private Object random1k; + + @Setup(Level.Trial) + public void setup() { + mergeSort = Clj.fn("sorts.merge-sort", "merge-sort"); + quickSort = Clj.fn("sorts.quick-sort", "quick-sort"); + heapSort = Clj.fn("sorts.heap-sort", "heap-sort"); + timSort = Clj.fn("sorts.tim-sort", "tim-sort"); + insertionSort = Clj.fn("sorts.insertion-sort", "insertion-sort"); + shellSort = Clj.fn("sorts.shell-sort", "shell-sort"); + countingSort = Clj.fn("sorts.counting-sort", "counting-sort"); + + IFn randomInts = Clj.fixture("random-ints"); + random5k = randomInts.invoke(5000); + // Counting sort allocates a bucket per distinct value: keep the range small. + smallRange5k = randomInts.invoke(5000, 10000, 42); + random2k = randomInts.invoke(2000); + random1k = randomInts.invoke(1000); + } + + @Benchmark + public Object mergeSort5k() { + return mergeSort.invoke(random5k); + } + + @Benchmark + public Object quickSort5k() { + return quickSort.invoke(random5k); + } + + @Benchmark + public Object heapSort5k() { + return heapSort.invoke(random5k); + } + + @Benchmark + public Object shellSort5k() { + return shellSort.invoke(random5k); + } + + @Benchmark + public Object countingSort5k() { + return countingSort.invoke(smallRange5k); + } + + @Benchmark + public Object timSort2k() { + return timSort.invoke(random2k); + } + + @Benchmark + public Object insertionSort1k() { + return insertionSort.invoke(random1k); + } +} diff --git a/bench/src/jmh/java/clojure_algorithms/bench/StringsBenchmark.java b/bench/src/jmh/java/clojure_algorithms/bench/StringsBenchmark.java new file mode 100644 index 0000000..0f32faf --- /dev/null +++ b/bench/src/jmh/java/clojure_algorithms/bench/StringsBenchmark.java @@ -0,0 +1,80 @@ +package clojure_algorithms.bench; + +import clojure.lang.IFn; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; + +@State(Scope.Benchmark) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class StringsBenchmark { + private IFn knuthMorrisPratt; + private IFn zFindPattern; + private IFn rabinKarp; + private IFn boyerMooreHorspool; + private IFn levenshtein; + private IFn jaroWinkler; + private IFn manacher; + + private String text20k; + private String pattern; + private String wordA; + private String wordB; + private String text2k; + + @Setup(Level.Trial) + public void setup() { + knuthMorrisPratt = Clj.fn("strings.knuth-morris-pratt", "knuth-morris-pratt"); + zFindPattern = Clj.fn("strings.z-function", "find-pattern"); + rabinKarp = Clj.fn("strings.rabin-karp", "rabin-karp"); + boyerMooreHorspool = Clj.fn("strings.boyer-moore-horspool", "boyer-moore-horspool-search"); + levenshtein = Clj.fn("strings.levenshtein-distance", "levenshtein-distance"); + jaroWinkler = Clj.fn("strings.jaro-winkler", "jaro-winkler"); + manacher = Clj.fn("strings.manacher", "palindromic-string"); + + IFn randomText = Clj.fixture("random-text"); + // Small alphabet => many partial matches, which stresses the matchers. + text20k = (String) randomText.invoke(20000, 4, 7L); + pattern = text20k.substring(15000, 15020); + wordA = (String) randomText.invoke(300, 26, 1L); + wordB = (String) randomText.invoke(300, 26, 2L); + text2k = (String) randomText.invoke(2000, 3, 9L); + } + + @Benchmark + public Object knuthMorrisPratt20k() { + return knuthMorrisPratt.invoke(text20k, pattern); + } + + @Benchmark + public Object zFunctionFindPattern20k() { + return zFindPattern.invoke(pattern, text20k); + } + + @Benchmark + public Object rabinKarp20k() { + return rabinKarp.invoke(pattern, text20k); + } + + @Benchmark + public Object boyerMooreHorspool20k() { + return boyerMooreHorspool.invoke(text20k, pattern); + } + + @Benchmark + public Object levenshtein300() { + return levenshtein.invoke(wordA, wordB); + } + + @Benchmark + public Object jaroWinkler300() { + return jaroWinkler.invoke(wordA, wordB); + } + + @Benchmark + public Object manacherLongestPalindrome2k() { + return manacher.invoke(text2k); + } +} diff --git a/third-party/codspeed-jvm b/third-party/codspeed-jvm new file mode 160000 index 0000000..af05f6f --- /dev/null +++ b/third-party/codspeed-jvm @@ -0,0 +1 @@ +Subproject commit af05f6f316a9f520ef3d7f57bee4438ce30c6191