8061281: Microbenchmark suite build support, directory layout and sample benchmarks

8061282: Migrate jmh-jdk-microbenchmarks into the JDK

Co-authored-by: Magnus Ihse Bursie <magnus.ihse.bursie@oracle.com>
Co-authored-by: Erik Joelsson <erik.joelsson@oracle.com>
Co-authored-by: Staffan Friberg <sfriberg@kth.se>
Reviewed-by: ecaspole, mchung, erikj, ihse
This commit is contained in:
Claes Redestad 2018-11-16 23:39:51 +01:00
parent 14b7467279
commit 7a30c97753
247 changed files with 26097 additions and 13 deletions

View File

@ -24,12 +24,14 @@
<li><a href="#test-selection">Test selection</a><ul>
<li><a href="#jtreg">JTReg</a></li>
<li><a href="#gtest">Gtest</a></li>
<li><a href="#microbenchmarks">Microbenchmarks</a></li>
<li><a href="#special-tests">Special tests</a></li>
</ul></li>
<li><a href="#test-results-and-summary">Test results and summary</a></li>
<li><a href="#test-suite-control">Test suite control</a><ul>
<li><a href="#jtreg-keywords">JTReg keywords</a></li>
<li><a href="#gtest-keywords">Gtest keywords</a></li>
<li><a href="#microbenchmark-keywords">Microbenchmark keywords</a></li>
</ul></li>
</ul>
</nav>
@ -44,9 +46,11 @@ $ make test TEST=jdk_lang
$ make test-only TEST=&quot;gtest:LogTagSet gtest:LogTagSetDescriptions&quot; GTEST=&quot;REPEAT=-1&quot;
$ make test TEST=&quot;hotspot:hotspot_gc&quot; JTREG=&quot;JOBS=1;TIMEOUT=8;VM_OPTIONS=-XshowSettings -Xlog:gc+ref=debug&quot;
$ make test TEST=&quot;jtreg:test/hotspot:hotspot_gc test/hotspot/jtreg/native_sanity/JniVersion.java&quot;
$ make test TEST=&quot;micro:java.lang.reflect&quot; MICRO=&quot;FORK=1;WARMUP_ITER=2&quot;
$ make exploded-test TEST=tier2</code></pre>
<h3 id="configuration">Configuration</h3>
<p>To be able to run JTReg tests, <code>configure</code> needs to know where to find the JTReg test framework. If it is not picked up automatically by configure, use the <code>--with-jtreg=&lt;path to jtreg home&gt;</code> option to point to the JTReg framework. Note that this option should point to the JTReg home, i.e. the top directory, containing <code>lib/jtreg.jar</code> etc. (An alternative is to set the <code>JT_HOME</code> environment variable to point to the JTReg home before running <code>configure</code>.)</p>
<p>To be able to run microbenchmarks, <code>configure</code> needs to know where to find the JMH dependency. Use <code>--with-jmh=&lt;path to JMH jars&gt;</code> to point to a directory containing the core JMH and transitive dependencies. The recommended dependencies can be retrieved by running <code>sh make/devkit/createJMHBundle.sh</code>, after which <code>--with-jmh=build/jmh/jars</code> should work.</p>
<h2 id="test-selection">Test selection</h2>
<p>All functionality is available using the <code>test</code> make target. In this use case, the test or tests to be executed is controlled using the <code>TEST</code> variable. To speed up subsequent test runs with no source code changes, <code>test-only</code> can be used instead, which do not depend on the source and test image build.</p>
<p>For some common top-level tests, direct make targets have been generated. This includes all JTReg test groups, the hotspot gtest, and custom tests (if present). This means that <code>make test-tier1</code> is equivalent to <code>make test TEST=&quot;tier1&quot;</code>, but the latter is more tab-completion friendly. For more complex test runs, the <code>test TEST=&quot;x&quot;</code> solution needs to be used.</p>
@ -61,6 +65,9 @@ $ make exploded-test TEST=tier2</code></pre>
<p>Since the Hotspot Gtest suite is so quick, the default is to run all tests. This is specified by just <code>gtest</code>, or as a fully qualified test descriptor <code>gtest:all</code>.</p>
<p>If you want, you can single out an individual test or a group of tests, for instance <code>gtest:LogDecorations</code> or <code>gtest:LogDecorations.level_test_vm</code>. This can be particularly useful if you want to run a shaky test repeatedly.</p>
<p>For Gtest, there is a separate test suite for each JVM variant. The JVM variant is defined by adding <code>/&lt;variant&gt;</code> to the test descriptor, e.g. <code>gtest:Log/client</code>. If you specify no variant, gtest will run once for each JVM variant present (e.g. server, client). So if you only have the server JVM present, then <code>gtest:all</code> will be equivalent to <code>gtest:all/server</code>.</p>
<h3 id="microbenchmarks">Microbenchmarks</h3>
<p>Which microbenchmarks to run is selected using a regular expression following the <code>micro:</code> test descriptor, e.g., <code>micro:java.lang.reflect</code>. This delegates the test selection to JMH, meaning package name, class name and even benchmark method names can be used to select tests.</p>
<p>Using special characters like <code>|</code> in the regular expression is possible, but needs to be escaped multiple times: <code>micro:ArrayCopy\\\\\|reflect</code>.</p>
<h3 id="special-tests">Special tests</h3>
<p>A handful of odd tests that are not covered by any other testing framework are accessible using the <code>special:</code> test descriptor. Currently, this includes <code>failure-handler</code> and <code>make</code>.</p>
<ul>
@ -127,5 +134,22 @@ TEST FAILURE</code></pre>
<h4 id="options-1">OPTIONS</h4>
<p>Additional options to the Gtest test framework.</p>
<p>Use <code>GTEST=&quot;OPTIONS=--help&quot;</code> to see all available Gtest options.</p>
<h3 id="microbenchmark-keywords">Microbenchmark keywords</h3>
<h4 id="fork">FORK</h4>
<p>Override the number of benchmark forks to spawn. Same as specifying <code>-f &lt;num&gt;</code>.</p>
<h4 id="iter">ITER</h4>
<p>Number of measurement iterations per fork. Same as specifying <code>-i &lt;num&gt;</code>.</p>
<h4 id="time">TIME</h4>
<p>Amount of time to spend in each measurement iteration, in seconds. Same as specifying <code>-r &lt;num&gt;</code></p>
<h4 id="warmup_iter">WARMUP_ITER</h4>
<p>Number of warmup iterations to run before the measurement phase in each fork. Same as specifying <code>-wi &lt;num&gt;</code>.</p>
<h4 id="warmup_time">WARMUP_TIME</h4>
<p>Amount of time to spend in each warmup iteration. Same as specifying <code>-w &lt;num&gt;</code>.</p>
<h4 id="results_format">RESULTS_FORMAT</h4>
<p>Specify to have the test run save a log of the values. Accepts the same values as <code>-rff</code>, i.e., <code>text</code>, <code>csv</code>, <code>scsv</code>, <code>json</code>, or <code>latex</code>.</p>
<h4 id="vm_options-1">VM_OPTIONS</h4>
<p>Additional VM arguments to provide to forked off VMs. Same as <code>-jvmArgs &lt;args&gt;</code></p>
<h4 id="options-2">OPTIONS</h4>
<p>Additional arguments to send to JMH.</p>
</body>
</html>

View File

@ -26,6 +26,7 @@ Some example command-lines:
$ make test-only TEST="gtest:LogTagSet gtest:LogTagSetDescriptions" GTEST="REPEAT=-1"
$ make test TEST="hotspot:hotspot_gc" JTREG="JOBS=1;TIMEOUT=8;VM_OPTIONS=-XshowSettings -Xlog:gc+ref=debug"
$ make test TEST="jtreg:test/hotspot:hotspot_gc test/hotspot/jtreg/native_sanity/JniVersion.java"
$ make test TEST="micro:java.lang.reflect" MICRO="FORK=1;WARMUP_ITER=2"
$ make exploded-test TEST=tier2
### Configuration
@ -37,6 +38,12 @@ Note that this option should point to the JTReg home, i.e. the top directory,
containing `lib/jtreg.jar` etc. (An alternative is to set the `JT_HOME`
environment variable to point to the JTReg home before running `configure`.)
To be able to run microbenchmarks, `configure` needs to know where to find
the JMH dependency. Use `--with-jmh=<path to JMH jars>` to point to a directory
containing the core JMH and transitive dependencies. The recommended dependencies
can be retrieved by running `sh make/devkit/createJMHBundle.sh`, after which
`--with-jmh=build/jmh/jars` should work.
## Test selection
All functionality is available using the `test` make target. In this use case,
@ -104,6 +111,16 @@ is defined by adding `/<variant>` to the test descriptor, e.g.
variant present (e.g. server, client). So if you only have the server JVM
present, then `gtest:all` will be equivalent to `gtest:all/server`.
### Microbenchmarks
Which microbenchmarks to run is selected using a regular expression
following the `micro:` test descriptor, e.g., `micro:java.lang.reflect`. This
delegates the test selection to JMH, meaning package name, class name and even
benchmark method names can be used to select tests.
Using special characters like `|` in the regular expression is possible, but
needs to be escaped multiple times: `micro:ArrayCopy\\\\\|reflect`.
### Special tests
A handful of odd tests that are not covered by any other testing framework are
@ -253,6 +270,35 @@ Additional options to the Gtest test framework.
Use `GTEST="OPTIONS=--help"` to see all available Gtest options.
### Microbenchmark keywords
#### FORK
Override the number of benchmark forks to spawn. Same as specifying `-f <num>`.
#### ITER
Number of measurement iterations per fork. Same as specifying `-i <num>`.
#### TIME
Amount of time to spend in each measurement iteration, in seconds. Same as
specifying `-r <num>`
#### WARMUP_ITER
Number of warmup iterations to run before the measurement phase in each fork.
Same as specifying `-wi <num>`.
#### WARMUP_TIME
Amount of time to spend in each warmup iteration. Same as specifying `-w <num>`.
#### RESULTS_FORMAT
Specify to have the test run save a log of the values. Accepts the same values
as `-rff`, i.e., `text`, `csv`, `scsv`, `json`, or `latex`.
#### VM_OPTIONS
Additional VM arguments to provide to forked off VMs. Same as `-jvmArgs <args>`
#### OPTIONS
Additional arguments to send to JMH.
---
# Override some definitions in the global css file that are not optimal for
# this document.

View File

@ -103,6 +103,7 @@ help:
$(info $(_) # make test TEST="jdk_lang gtest:all")
$(info $(_) JTREG="OPT1=x;OPT2=y" # Control the JTREG test harness)
$(info $(_) GTEST="OPT1=x;OPT2=y" # Control the GTEST test harness)
$(info $(_) MICRO="OPT1=x;OPT2=y" # Control the MICRO test harness)
$(info $(_) TEST_OPTS="OPT1=x;..." # Generic control of all test harnesses)
$(info $(_) TEST_VM_OPTS="ARG ..." # Same as setting TEST_OPTS to VM_OPTIONS="ARG ...")
$(info )

View File

@ -50,7 +50,7 @@ ifeq ($(HAS_SPEC),)
# Make control variables, handled by Init.gmk
INIT_CONTROL_VARIABLES += LOG CONF CONF_NAME SPEC JOBS TEST_JOBS CONF_CHECK \
COMPARE_BUILD JTREG GTEST TEST_OPTS TEST_VM_OPTS
COMPARE_BUILD JTREG GTEST MICRO TEST_OPTS TEST_VM_OPTS
# All known make control variables
MAKE_CONTROL_VARIABLES := $(INIT_CONTROL_VARIABLES) TEST JDK_FILTER

View File

@ -493,7 +493,7 @@ ALL_EXPLODED_TEST_TARGETS := $(addprefix exploded-test-, $(ALL_EXPLODED_TESTS))
ALL_TARGETS += $(ALL_TEST_TARGETS) $(ALL_EXPLODED_TEST_TARGETS)
################################################################################
# Build tests
# Build tests and microbenchmarks
#
prepare-test-image:
@ -543,11 +543,15 @@ ifeq ($(BUILD_FAILURE_HANDLER), true)
-f BuildFailureHandler.gmk images)
endif
build-microbenchmark:
+($(CD) $(TOPDIR)/make && $(MAKE) $(MAKE_ARGS) -f test/BuildMicrobenchmark.gmk)
ALL_TARGETS += prepare-test-image build-test-hotspot-jtreg-native \
test-image-hotspot-jtreg-native build-test-jdk-jtreg-native \
test-image-jdk-jtreg-native build-test-lib build-test-failure-handler \
test-failure-handler test-image-failure-handler test-image-hotspot-gtest \
test-image-hotspot-jtreg-graal build-test-hotspot-jtreg-graal
test-image-hotspot-jtreg-graal build-test-hotspot-jtreg-graal \
build-microbenchmark
################################################################################
# Run tests
@ -789,6 +793,8 @@ else
jrtfs-jar: interim-langtools
build-microbenchmark: interim-langtools jdk.unsupported java.management
ifeq ($(ENABLE_GENERATE_CLASSLIST), true)
ifeq ($(CREATE_BUILDJDK), true)
# If creating a buildjdk, the interim image needs to be based on that.
@ -1023,6 +1029,10 @@ test-image: prepare-test-image \
test-image-jdk-jtreg-native test-image-failure-handler \
test-image-demos-jdk $(JVM_TEST_IMAGE_TARGETS)
ifneq ($(JMH_CORE_JAR), )
test-image: build-microbenchmark
endif
################################################################################
# all-images builds all our deliverables as images.

View File

@ -237,13 +237,11 @@ ifneq ($(TEST_OPTS), )
$(info Running tests using TEST_OPTS control variable '$(TEST_OPTS)')
endif
### Jtreg
$(eval $(call SetTestOpt,VM_OPTIONS,JTREG))
$(eval $(call SetTestOpt,JAVA_OPTIONS,JTREG))
$(eval $(call SetTestOpt,VM_OPTIONS,GTEST))
$(eval $(call SetTestOpt,JAVA_OPTIONS,GTEST))
$(eval $(call SetTestOpt,AOT_MODULES,JTREG))
$(eval $(call SetTestOpt,AOT_MODULES,GTEST))
$(eval $(call SetTestOpt,JOBS,JTREG))
$(eval $(call SetTestOpt,TIMEOUT_FACTOR,JTREG))
@ -259,6 +257,12 @@ ifneq ($(JTREG), )
$(info Running tests using JTREG control variable '$(JTREG)')
endif
### Gtest
$(eval $(call SetTestOpt,VM_OPTIONS,GTEST))
$(eval $(call SetTestOpt,JAVA_OPTIONS,GTEST))
$(eval $(call SetTestOpt,AOT_MODULES,GTEST))
$(eval $(call ParseKeywordVariable, GTEST, \
SINGLE_KEYWORDS := REPEAT AOT_MODULES, \
STRING_KEYWORDS := OPTIONS VM_OPTIONS JAVA_OPTIONS, \
@ -269,6 +273,21 @@ ifneq ($(GTEST), )
$(info Running tests using GTEST control variable '$(GTEST)')
endif
### Microbenchmarks
$(eval $(call SetTestOpt,VM_OPTIONS,MICRO))
$(eval $(call SetTestOpt,JAVA_OPTIONS,MICRO))
$(eval $(call ParseKeywordVariable, MICRO, \
SINGLE_KEYWORDS := ITER FORK TIME WARMUP_ITER WARMUP_TIME, \
STRING_KEYWORDS := OPTIONS JAVA_OPTIONS VM_OPTIONS RESULTS_FORMAT TEST_JDK BENCHMARKS_JAR, \
))
ifneq ($(MICRO), )
# Inform the user
$(info Running tests using MICRO control variable '$(MICRO)')
endif
################################################################################
# Component-specific Jtreg settings
@ -325,6 +344,24 @@ define ParseGtestTestSelection
)
endef
# Helper function to determine if a test specification is a microbenchmark test
#
# It is a microbenchmark test if it is either "micro", or "micro:" followed by an optional
# test filter string.
define ParseMicroTestSelection
$(if $(filter micro%, $1), \
$(if $(filter micro, $1), \
micro:all \
, \
$(if $(filter micro:, $1), \
micro:all \
, \
$1 \
) \
) \
)
endef
# Helper function that removes the TOPDIR part
CleanupJtregPath = \
$(strip $(patsubst %/, %, $(subst $(JTREG_TOPDIR)/,, $1)))
@ -437,6 +474,9 @@ $(foreach test, $(TEST), \
$(if $(strip $(PARSED_TESTS)), , \
$(eval PARSED_TESTS += $(call ParseGtestTestSelection, $(test))) \
) \
$(if $(strip $(PARSED_TESTS)), , \
$(eval PARSED_TESTS += $(call ParseMicroTestSelection, $(test))) \
) \
$(if $(strip $(PARSED_TESTS)), , \
$(eval PARSED_TESTS += $(call ParseJtregTestSelection, $(test))) \
) \
@ -560,6 +600,113 @@ endef
################################################################################
### Rules for Microbenchmarks
# Helper function for SetupRunMicroTest. Set a MICRO_* variable from, in order:
# 1) Specified by user on command line
# 2) Generic default
#
# Note: No spaces are allowed around the arguments.
# Arg $1 The test ID (i.e. $1 in SetupRunMicroTest)
# Arg $2 Base variable, e.g. MICRO_TEST_JDK
# Arg $3 The default value (optional)
define SetMicroValue
ifneq ($$($2), )
$1_$2 := $$($2)
else
ifneq ($3, )
$1_$2 := $3
endif
endif
endef
SetupRunMicroTest = $(NamedParamsMacroTemplate)
define SetupRunMicroTestBody
$1_TEST_RESULTS_DIR := $$(TEST_RESULTS_DIR)/$1
$1_TEST_SUPPORT_DIR := $$(TEST_SUPPORT_DIR)/$1
$1_EXITCODE := $$($1_TEST_RESULTS_DIR)/exitcode.txt
$1_TEST_NAME := $$(strip $$(patsubst micro:%, %, $$($1_TEST)))
$$(eval $$(call SetMicroValue,$1,MICRO_BENCHMARKS_JAR,$$(TEST_IMAGE_DIR)/micro/benchmarks.jar))
$$(eval $$(call SetMicroValue,$1,MICRO_TEST_JDK,$$(JDK_IMAGE_DIR)))
$$(eval $$(call SetMicroValue,$1,MICRO_JAVA_OPTIONS))
# Current tests needs to open java.io
$1_MICRO_JAVA_OPTIONS += --add-opens=java.base/java.io=ALL-UNNAMED
# Save output as JSON or CSV file
ifneq ($$(MICRO_RESULTS_FORMAT), )
$1_MICRO_BASIC_OPTIONS += -rf $$(MICRO_RESULTS_FORMAT) -rff $$($1_TEST_RESULTS_DIR)/jmh-result.$(MICRO_RESULTS_FORMAT)
endif
ifneq ($$(MICRO_VM_OPTIONS)$$(MICRO_JAVA_OPTIONS), )
$1_MICRO_VM_OPTIONS := -jvmArgs $$(MICRO_VM_OPTIONS) $$(MICRO_JAVA_OPTIONS)
endif
ifneq ($$(MICRO_ITER), )
$1_MICRO_ITER := -i $$(MICRO_ITER)
endif
ifneq ($$(MICRO_FORK), )
$1_MICRO_FORK := -f $$(MICRO_FORK)
endif
ifneq ($$(MICRO_TIME), )
$1_MICRO_TIME := -r $$(MICRO_TIME)
endif
ifneq ($$(MICRO_WARMUP_ITER), )
$1_MICRO_WARMUP_ITER := -wi $$(MICRO_WARMUP_ITER)
endif
ifneq ($$(MICRO_WARMUP_TIME), )
$1_MICRO_WARMUP_TIME := -w $$(MICRO_WARMUP_TIME)
endif
run-test-$1:
$$(call LogWarn)
$$(call LogWarn, Running test '$$($1_TEST)')
$$(call MakeDir, $$($1_TEST_RESULTS_DIR) $$($1_TEST_SUPPORT_DIR))
$$(call ExecuteWithLog, $$($1_TEST_SUPPORT_DIR)/micro, \
$$($1_MICRO_TEST_JDK)/bin/java $$($1_MICRO_JAVA_OPTIONS) -jar $$($1_MICRO_BENCHMARKS_JAR) \
$$($1_MICRO_ITER) $$($1_MICRO_FORK) $$($1_MICRO_TIME) \
$$($1_MICRO_WARMUP_ITER) $$($1_MICRO_WARMUP_TIME) \
$$($1_MICRO_VM_OPTIONS) $$($1_MICRO_BASIC_OPTIONS) $$(MICRO_OPTIONS) \
$$($1_TEST_NAME) \
> >($(TEE) $$($1_TEST_RESULTS_DIR)/micro.txt) \
&& $$(ECHO) $$$$? > $$($1_EXITCODE) \
|| $$(ECHO) $$$$? > $$($1_EXITCODE) \
)
$1_RESULT_FILE := $$($1_TEST_RESULTS_DIR)/micro.txt
parse-test-$1: run-test-$1
$$(call LogWarn, Finished running test '$$($1_TEST)')
$$(call LogWarn, Test report is stored in $$(strip \
$$(subst $$(TOPDIR)/, , $$($1_TEST_RESULTS_DIR))))
$$(if $$(wildcard $$($1_EXITCODE)), \
$$(eval $1_EXIT_CODE := $$(shell $$(CAT) $$($1_EXITCODE))) \
$$(if $$(filter 0, $$($1_EXIT_CODE)), \
$$(eval $1_PASSED := 1) \
$$(eval $1_ERROR := 0) \
, \
$$(eval $1_PASSED := 0) \
$$(eval $1_ERROR := 1) \
) \
$$(eval $1_FAILED := 0) \
$$(eval $1_TOTAL := $$(shell \
$$(EXPR) $$($1_PASSED) + $$($1_ERROR))) \
, \
$$(eval $1_PASSED := 0) \
$$(eval $1_FAILED := 0) \
$$(eval $1_ERROR := 1) \
$$(eval $1_TOTAL := 1) \
)
$1: run-test-$1 parse-test-$1
TARGETS += $1
endef
################################################################################
### Rules for Jtreg
# Helper function for SetupRunJtregTest. Set a JTREG_* variable from, in order:
@ -849,6 +996,9 @@ endef
UseGtestTestHandler = \
$(if $(filter gtest:%, $1), true)
UseMicroTestHandler = \
$(if $(filter micro:%, $1), true)
UseJtregTestHandler = \
$(if $(filter jtreg:%, $1), true)
@ -870,6 +1020,11 @@ $(foreach test, $(TESTS_TO_RUN), \
TEST := $(test), \
)) \
) \
$(if $(call UseMicroTestHandler, $(test)), \
$(eval $(call SetupRunMicroTest, $(TEST_ID), \
TEST := $(test), \
)) \
) \
$(if $(call UseJtregTestHandler, $(test)), \
$(eval $(call SetupRunJtregTest, $(TEST_ID), \
TEST := $(test), \

View File

@ -180,6 +180,9 @@ TOOLCHAIN_MISC_CHECKS
# Setup the JTReg Regression Test Harness.
TOOLCHAIN_SETUP_JTREG
# Setup the Java Microbenchmark Harness (JMH)
LIB_TESTS_SETUP_JMH
# Setup Jib dependency tool
TOOLCHAIN_SETUP_JIB

View File

@ -55,3 +55,65 @@ AC_DEFUN_ONCE([LIB_TESTS_SETUP_GRAALUNIT],
AC_SUBST(GRAALUNIT_LIB)
])
###############################################################################
#
# Setup and check the Java Microbenchmark Harness
#
AC_DEFUN_ONCE([LIB_TESTS_SETUP_JMH],
[
AC_ARG_WITH(jmh, [AS_HELP_STRING([--with-jmh],
[Java Microbenchmark Harness for building the OpenJDK Microbenchmark Suite])])
AC_MSG_CHECKING([for jmh (Java Microbenchmark Harness)])
if test "x$with_jmh" = xno || test "x$with_jmh" = x; then
AC_MSG_RESULT([no, disabled])
elif test "x$with_jmh" = xyes; then
AC_MSG_RESULT([no, error])
AC_MSG_ERROR([--with-jmh requires a directory containing all jars needed by JMH])
else
# Path specified
JMH_HOME="$with_jmh"
if test ! -d [$JMH_HOME]; then
AC_MSG_RESULT([no, error])
AC_MSG_ERROR([$JMH_HOME does not exist or is not a directory])
fi
BASIC_FIXUP_PATH([JMH_HOME])
jar_names="jmh-core jmh-generator-annprocess jopt-simple commons-math3"
for jar in $jar_names; do
found_jar_files=$($ECHO $(ls $JMH_HOME/$jar-*.jar 2> /dev/null))
if test "x$found_jar_files" = x; then
AC_MSG_RESULT([no])
AC_MSG_ERROR([--with-jmh does not contain $jar-*.jar])
elif ! test -e "$found_jar_files"; then
AC_MSG_RESULT([no])
AC_MSG_ERROR([--with-jmh contain multiple $jar-*.jar: $found_jar_files])
fi
found_jar_var_name=found_${jar//-/_}
eval $found_jar_var_name='"'$found_jar_files'"'
done
AC_MSG_RESULT([yes])
JMH_CORE_JAR=$found_jmh_core
JMH_GENERATOR_JAR=$found_jmh_generator_annprocess
JMH_JOPT_SIMPLE_JAR=$found_jopt_simple
JMH_COMMONS_MATH_JAR=$found_commons_math3
if [ [[ "$JMH_CORE_JAR" =~ jmh-core-(.*)\.jar$ ]] ] ; then
JMH_VERSION=${BASH_REMATCH[[1]]}
else
JMH_VERSION=unknown
fi
AC_MSG_NOTICE([JMH core version: $JMH_VERSION])
fi
AC_SUBST(JMH_CORE_JAR)
AC_SUBST(JMH_GENERATOR_JAR)
AC_SUBST(JMH_JOPT_SIMPLE_JAR)
AC_SUBST(JMH_COMMONS_MATH_JAR)
AC_SUBST(JMH_VERSION)
])

View File

@ -355,6 +355,12 @@ ENABLE_LIBFFI_BUNDLING:=@ENABLE_LIBFFI_BUNDLING@
LIBFFI_LIB_FILE:=@LIBFFI_LIB_FILE@
GRAALUNIT_LIB := @GRAALUNIT_LIB@
JMH_CORE_JAR := @JMH_CORE_JAR@
JMH_GENERATOR_JAR := @JMH_GENERATOR_JAR@
JMH_JOPT_SIMPLE_JAR := @JMH_JOPT_SIMPLE_JAR@
JMH_COMMONS_MATH_JAR := @JMH_COMMONS_MATH_JAR@
JMH_VERSION := @JMH_VERSION@
# Source file for cacerts
CACERTS_FILE=@CACERTS_FILE@

View File

@ -72,6 +72,9 @@ ALL_NAMED_TESTS += $(JTREG_TEST_GROUPS)
# Add Gtest
ALL_NAMED_TESTS += gtest
# Add microbenchmarks
ALL_NAMED_TESTS += micro
# Find make test targets
MAKE_TEST_TARGETS := $(shell $(MAKE) -s --no-print-directory $(MAKE_ARGS) \
SPEC=$(SPEC) -f $(TOPDIR)/test/make/TestMake.gmk print-targets)

View File

@ -43,6 +43,7 @@ FALSE_FIND_PATTERN:=-name FILE_NAME_THAT_DOESNT_EXIST
# For this to work, the source files must exist when the makefile is
# parsed.
# SRCS:=List of directories in where to find files to add to archive
# BIN:=Directory where to store build control files
# SUFFIXES:=File suffixes to include in jar
# INCLUDES:=List of directories/packages in SRCS that should be included
# EXCLUDES:=List of directories/packages in SRCS that should be excluded
@ -62,10 +63,11 @@ define SetupJarArchiveBody
$1_JARMAIN:=$(strip $$($1_JARMAIN))
$1_JARNAME:=$$(notdir $$($1_JAR))
$1_MANIFEST_FILE:=$$(dir $$($1_JAR))_the.$$($1_JARNAME)_manifest
$1_DELETESS_FILE:=$$(dir $$($1_JAR))_the.$$($1_JARNAME)_deletess
$1_DELETES_FILE:=$$(dir $$($1_JAR))_the.$$($1_JARNAME)_deletes
$1_BIN:=$$(dir $$($1_JAR))
$1_JAR_OUTPUT_DIR := $$(patsubst %/, %, $$(dir $$($1_JAR)))
$$(call SetIfEmpty, $1_BIN, $$($1_JAR_OUTPUT_DIR))
$1_MANIFEST_FILE:=$$($1_BIN)/_the.$$($1_JARNAME)_manifest
$1_DELETESS_FILE:=$$($1_BIN)/_the.$$($1_JARNAME)_deletess
$1_DELETES_FILE:=$$($1_BIN)/_the.$$($1_JARNAME)_deletes
$$(call SetIfEmpty, $1_JAR_CMD, $$(JAR))
ifeq (,$$($1_SUFFIXES))
@ -231,11 +233,12 @@ define SetupJarArchiveBody
$1_VARDEPS := $$($1_JAR_CMD) $$($1_JAR_CREATE_OPTIONS) $$($1_MANIFEST) \
$$($1_JARMAIN) $$($1_EXTRA_MANIFEST_ATTR) $$($1_ORIG_DEPS) $$($1_SRCS) \
$$($1_INCLUDES) $$($1_EXCLUDES) $$($1_EXCLUDE_FILES) $$($1_EXTRA_FILES)
$1_VARDEPS_FILE := $$(call DependOnVariable, $1_VARDEPS, $$(dir $$($1_JAR))_the.$$($1_JARNAME).vardeps)
$1_VARDEPS_FILE := $$(call DependOnVariable, $1_VARDEPS, $$($1_BIN)/_the.$$($1_JARNAME).vardeps)
# Here is the rule that creates/updates the jar file.
$$($1_JAR) : $$($1_DEPENDENCIES) $$($1_MANIFEST) $$($1_VARDEPS_FILE)
$$(call MakeTargetDir)
$$(call MakeDir, $$($1_BIN))
$$($1_GREP_INCLUDE_OUTPUT)
$$($1_GREP_EXCLUDE_OUTPUT)
# If the vardeps file is part of the newer prereq list, it means that

View File

@ -243,7 +243,7 @@ var getJibProfilesCommon = function (input, data) {
// These are the base setttings for all the main build profiles.
common.main_profile_base = {
dependencies: ["boot_jdk", "gnumake", "jtreg", "jib", "autoconf"],
dependencies: ["boot_jdk", "gnumake", "jtreg", "jib", "autoconf", "jmh"],
default_make_targets: ["product-bundles", "test-bundles"],
configure_args: concat(["--enable-jtreg-failure-handler"],
"--with-exclude-translations=de,es,fr,it,ko,pt_BR,sv,ca,tr,cs,sk,ja_JP_A,ja_JP_HA,ja_JP_HI,ja_JP_I,zh_TW,zh_HK",
@ -892,6 +892,12 @@ var getJibProfilesDependencies = function (input, common) {
environment_path: input.get("jtreg", "install_path") + "/jtreg/bin"
},
jmh: {
organization: common.organization,
ext: "tar.gz",
revision: "1.21+1.0"
},
gnumake: {
organization: common.organization,
ext: "tar.gz",

View File

@ -0,0 +1,50 @@
#!/bin/bash -e
#
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# Create a bundle in the build directory, containing what's needed to
# build and run JMH microbenchmarks from the OpenJDK build.
JMH_VERSION=1.21
COMMONS_MATH3_VERSION=3.2
JOPT_SIMPLE_VERSION=4.6
BUNDLE_NAME=jmh-$JMH_VERSION.tar.gz
SCRIPT_DIR="$(cd "$(dirname $0)" > /dev/null && pwd)"
BUILD_DIR="${SCRIPT_DIR}/../../build/jmh"
JAR_DIR="$BUILD_DIR/jars"
mkdir -p $BUILD_DIR $JAR_DIR
cd $JAR_DIR
rm -f *
wget http://central.maven.org/maven2/org/apache/commons/commons-math3/$COMMONS_MATH3_VERSION/commons-math3-$COMMONS_MATH3_VERSION.jar
wget http://central.maven.org/maven2/net/sf/jopt-simple/jopt-simple/$JOPT_SIMPLE_VERSION/jopt-simple-$JOPT_SIMPLE_VERSION.jar
wget http://central.maven.org/maven2/org/openjdk/jmh/jmh-core/$JMH_VERSION/jmh-core-$JMH_VERSION.jar
wget http://central.maven.org/maven2/org/openjdk/jmh/jmh-generator-annprocess/$JMH_VERSION/jmh-generator-annprocess-$JMH_VERSION.jar
tar -cvzf ../$BUNDLE_NAME *
echo "Created $BUILD_DIR/$BUNDLE_NAME"

View File

@ -0,0 +1,113 @@
#
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# This must be the first rule
default: all
include $(SPEC)
include MakeBase.gmk
include JavaCompilation.gmk
include SetupJavaCompilers.gmk
ifeq ($(JMH_CORE_JAR), )
$(info Error: JMH is missing. Please use configure --with-jmh.)
$(error Cannot continue)
endif
#### Variables
MICROBENCHMARK_SRC := $(TOPDIR)/test/micro
MICROBENCHMARK_JAR := $(IMAGES_OUTPUTDIR)/test/micro/benchmarks.jar
MICROBENCHMARK_OUTPUT := $(SUPPORT_OUTPUTDIR)/test/micro
MICROBENCHMARK_CLASSES := $(MICROBENCHMARK_OUTPUT)/classes
MICROBENCHMARK_JAR_BIN := $(MICROBENCHMARK_OUTPUT)/jar
JMH_UNPACKED_DIR := $(MICROBENCHMARK_OUTPUT)/jmh_jars
JMH_UNPACKED_JARS_DONE := $(JMH_UNPACKED_DIR)/_unpacked.marker
# External dependencies
JMH_COMPILE_JARS := $(JMH_CORE_JAR) $(JMH_GENERATOR_JAR)
JMH_RUNTIME_JARS := $(JMH_CORE_JAR) $(JMH_COMMONS_MATH_JAR) $(JMH_JOPT_SIMPLE_JAR)
MICROBENCHMARK_CLASSPATH := $(call PathList, $(JMH_COMPILE_JARS))
###
# Need double \n to get new lines and no trailing spaces
MICROBENCHMARK_MANIFEST := Build: $(FULL_VERSION)\n\
\nJMH-Version: $(JMH_VERSION)\n\
\nName: OpenJDK Microbenchmark Suite
#### Compile Targets
# Building microbenchmark requires the jdk.unsupported and java.management modules,
# and to have sjavac disabled.
$(eval $(call SetupJavaCompiler, MICROBENCHMARK_JAVA_COMPILER, \
JVM := $(JAVA) --add-modules jdk.unsupported --limit-modules java.management, \
JAVAC := $(NEW_JAVAC), \
DISABLE_SJAVAC := true, \
FLAGS := --upgrade-module-path $(JDK_OUTPUTDIR)/modules --system none $(DISABLE_WARNINGS), \
SERVER_DIR := $(SJAVAC_SERVER_DIR), \
SERVER_JVM := $(SJAVAC_SERVER_JAVA), \
))
# Build microbenchmark suite for the current JDK
$(eval $(call SetupJavaCompilation, BUILD_JDK_MICROBENCHMARK, \
SETUP := MICROBENCHMARK_JAVA_COMPILER, \
ADD_JAVAC_FLAGS := -cp $(MICROBENCHMARK_CLASSPATH) -Xlint -Werror, \
SRC := $(MICROBENCHMARK_SRC), \
BIN := $(MICROBENCHMARK_CLASSES), \
))
$(BUILD_JDK_MICROBENCHMARK): $(JMH_COMPILE_JARS)
# Unpacking dependencies for inclusion in the benchmark JARs
$(JMH_UNPACKED_JARS_DONE): $(JMH_RUNTIME_JARS)
$(RM) -r $(JMH_UNPACKED_DIR)
$(MKDIR) -p $(JMH_UNPACKED_DIR)
$(foreach jar, $(JMH_RUNTIME_JARS), \
$$($(UNZIP) -oq $(jar) -d $(JMH_UNPACKED_DIR)))
$(RM) -r $(JMH_UNPACKED_DIR)/META-INF
$(RM) $(JMH_UNPACKED_DIR)/*.xml
$(TOUCH) $@
# Create benchmarks JAR file with benchmarks for both the old and new JDK
$(eval $(call SetupJarArchive, BUILD_JDK_JAR, \
DEPENDENCIES := $(BUILD_JDK_MICROBENCHMARK) $(JMH_UNPACKED_JARS_DONE), \
SRCS := $(MICROBENCHMARK_CLASSES) $(JMH_UNPACKED_DIR), \
BIN := $(MICROBENCHMARK_JAR_BIN), \
SUFFIXES := .*, \
EXCLUDE_FILES:= _the.BUILD_JDK_MICROBENCHMARK_batch \
_the.BUILD_JDK_MICROBENCHMARK.vardeps _unpacked.marker, \
EXTRA_MANIFEST_ATTR := $(MICROBENCHMARK_MANIFEST), \
JARMAIN := org.openjdk.jmh.Main, \
JAR := $(MICROBENCHMARK_JAR), \
))
all: $(MICROBENCHMARK_JAR)
.PHONY: all

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import org.openjdk.jmh.infra.Blackhole;
import java.io.IOException;
import java.io.OutputStream;
public class BlackholedOutputStream extends OutputStream {
private final Blackhole bh;
public BlackholedOutputStream(Blackhole bh) {
this.bh = bh;
}
@Override
public void write(int b) throws IOException {
bh.consume(b);
}
@Override
public void write(byte[] b) throws IOException {
bh.consume(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
bh.consume(b);
}
}

View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
/**
* Tests the overheads of I/O API.
* This test is known to depend heavily on disk subsystem performance.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class FileChannelRead {
@Param("1000000")
private int fileSize;
private File f;
private FileChannel fc;
private ByteBuffer bb;
@Setup(Level.Trial)
public void beforeRun() throws IOException {
f = File.createTempFile("FileChannelReadBench", ".bin");
try (FileOutputStream fos = new FileOutputStream(f)) {
for (int i = 0; i < fileSize; i++) {
fos.write((byte) i);
}
}
bb = ByteBuffer.allocate(1);
}
@TearDown(Level.Trial)
public void afterRun() throws IOException {
f.delete();
}
@Setup(Level.Iteration)
public void beforeIteration() throws IOException {
fc = FileChannel.open(f.toPath(), StandardOpenOption.READ);
}
@TearDown(Level.Iteration)
public void afterIteration() throws IOException {
fc.close();
}
@Benchmark
public void test() throws IOException {
int ret = fc.read(bb);
bb.flip();
if (ret == -1) {
// start over
fc.position(0);
}
}
}

View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
/**
* Tests the overheads of I/O API.
* This test is known to depend heavily on disk subsystem performance.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class FileChannelWrite {
@Param("1000000")
private int fileSize;
private File f;
private FileChannel fc;
private ByteBuffer bb;
private int count;
@Setup(Level.Trial)
public void beforeRun() throws IOException {
f = File.createTempFile("FileChannelWriteBench", ".bin");
bb = ByteBuffer.allocate(1);
bb.put((byte) 47);
bb.flip();
}
@TearDown(Level.Trial)
public void afterRun() throws IOException {
f.delete();
}
@Setup(Level.Iteration)
public void beforeIteration() throws IOException {
fc = FileChannel.open(f.toPath(), StandardOpenOption.WRITE);
count = 0;
}
@TearDown(Level.Iteration)
public void afterIteration() throws IOException {
fc.close();
}
@Benchmark
public void test() throws IOException {
fc.write(bb);
bb.flip();
count++;
if (count >= fileSize) {
// start over
fc.position(0);
count = 0;
}
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
/**
* Tests the overheads of I/O API.
* This test is known to depend heavily on disk subsystem performance.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class FileRead {
@Param("1000000")
private int fileSize;
private File f;
private FileInputStream fis;
@Setup(Level.Trial)
public void beforeRun() throws IOException {
f = File.createTempFile("FileReadBench", ".bin");
try (FileOutputStream fos = new FileOutputStream(f)) {
for (int i = 0; i < fileSize; i++) {
fos.write((byte) i);
}
}
}
@TearDown(Level.Trial)
public void afterRun() throws IOException {
f.delete();
}
@Setup(Level.Iteration)
public void beforeIteration() throws FileNotFoundException {
fis = new FileInputStream(f);
}
@TearDown(Level.Iteration)
public void afterIteration() throws IOException {
fis.close();
}
@Benchmark
public void test() throws IOException {
int ret = fis.read();
if (ret == -1) {
// start over
fis.close();
fis = new FileInputStream(f);
}
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
/**
* Tests the overheads of I/O API.
* This test is known to depend heavily on disk subsystem performance.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class FileWrite {
@Param("1000000")
private int fileSize;
private File f;
private FileOutputStream fos;
private long count;
@Setup(Level.Trial)
public void beforeRun() throws IOException {
f = File.createTempFile("FileWriteBench", ".bin");
}
@TearDown(Level.Trial)
public void afterRun() throws IOException {
f.delete();
}
@Setup(Level.Iteration)
public void beforeIteration() throws FileNotFoundException {
fos = new FileOutputStream(f);
}
@TearDown(Level.Iteration)
public void afterIteration() throws IOException {
fos.close();
}
@Benchmark
public void test() throws IOException {
fos.write((byte) count);
count++;
if (count >= fileSize) {
// restart
fos.close();
fos = new FileOutputStream(f);
count = 0;
}
}
}

View File

@ -0,0 +1,244 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
/**
* A micro benchmark used to measure the performance impact from multi threaded access to ObjectStreamClass.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ObjectStreamClasses {
public Class<?>[] classes;
@Setup
public void setup() {
LinkedList<Class> queue = new LinkedList<Class>();
int i = 0;
while (true) {
// Loop until we get a ClassNotFoundException
// Maybe rewrite this considering the fact that there are 29
// inner classes available?
try {
Class clazz = Class.forName(ObjectStreamClasses.class.getName() + "$SerializableClass" + i++);
queue.add(clazz);
} catch (ClassNotFoundException e) {
break;
}
}
classes = new Class[queue.size()];
// Make ObjectStreamClass load all classes into the static map
i = 0;
while (!queue.isEmpty()) {
classes[i] = (Class) queue.remove();
i++;
}
}
/**
* Tests the static lookup function. Depending on JRE version the internal behavior is different but the general
* behavior is a synchronized call to some sort of static container.
*/
@Benchmark
public void testLookup(Blackhole bh) {
for (Class<?> klass : classes) {
bh.consume(ObjectStreamClass.lookup(klass));
}
}
static class SerializableClass0 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass1 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass2 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass3 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass4 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass5 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass6 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass7 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass8 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass9 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass10 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass11 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass12 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass13 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass14 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass15 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass16 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass17 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass18 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass19 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass20 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass21 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass22 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass23 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass24 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass25 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass26 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass27 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass28 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
static class SerializableClass29 extends SerializableClass {
private static final long serialVersionUID = 1L;
}
@SuppressWarnings("unused")
private static class SerializableClass implements Serializable {
private static final long serialVersionUID = 6107539118220989250L;
public Object objectField00 = new Object();
public Object objectField01 = new Object();
public Object objectField02 = new Object();
public Object objectField03 = new Object();
public Object objectField04 = new Object();
public Object objectField05 = new Object();
public Object objectField06 = new Object();
public Object objectField07 = new Object();
public Object objectField08 = new Object();
public Object objectField09 = new Object();
public Object objectField10 = new Object();
public Object objectField11 = new Object();
public Object objectField12 = new Object();
public Object objectField13 = new Object();
public Object objectField14 = new Object();
public Object objectField15 = new Object();
public Object objectField16 = new Object();
public Object objectField17 = new Object();
public Object objectField18 = new Object();
public Object objectField19 = new Object();
public Object objectField20 = new Object();
public Object objectField21 = new Object();
public Object objectField22 = new Object();
public Object objectField23 = new Object();
public Object objectField24 = new Object();
public Object objectField25 = new Object();
public Object objectField26 = new Object();
public Object objectField27 = new Object();
public Object objectField28 = new Object();
public Object objectField29 = new Object();
SerializableClass() {
super();
}
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
/**
* Tests the overheads of I/O API.
* This test is known to depend heavily on disk subsystem performance.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class RandomAccessRead {
@Param("1000000")
private int fileSize;
private RandomAccessFile raf;
private long offset;
private int deltaIndex;
private int[] deltas;
private File f;
@Setup(Level.Trial)
public void beforeRun() throws IOException {
f = File.createTempFile("RandomAccessBench", ".bin");
try (FileOutputStream fos = new FileOutputStream(f)) {
for (int i = 0; i < fileSize; i++) {
fos.write((byte) i);
}
}
deltas = new int[]{1, 2, 3, 5, 7, 11, 13, 17, 19, 23};
}
@TearDown(Level.Trial)
public void afterRun() throws IOException {
f.delete();
}
@Setup(Level.Iteration)
public void beforeIteration() throws IOException {
raf = new RandomAccessFile(f, "rw");
offset = 0;
deltaIndex = 0;
}
@TearDown(Level.Iteration)
public void afterIteration() throws IOException {
raf.close();
}
@Benchmark
public int test() throws IOException {
offset = offset + deltas[deltaIndex];
if (offset >= fileSize) {
offset = 0;
}
deltaIndex++;
if (deltaIndex >= deltas.length) {
deltaIndex = 0;
}
raf.seek(offset);
return raf.read();
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
/**
* Tests the overheads of I/O API.
* This test is known to depend heavily on disk subsystem performance.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class RandomAccessWrite {
@Param("1000000")
private int fileSize;
private File f;
private RandomAccessFile raf;
private long offset;
private int deltaIndex;
private int[] deltas;
@Setup(Level.Trial)
public void beforeRun() throws IOException {
f = File.createTempFile("RandomAccessBench", ".bin");
try (FileOutputStream fos = new FileOutputStream(f)) {
for (int i = 0; i < fileSize; i++) {
fos.write((byte) i);
}
}
deltas = new int[]{1, 2, 3, 5, 7, 11, 13, 17, 19, 23};
}
@TearDown(Level.Trial)
public void afterRun() throws IOException {
f.delete();
}
@Setup(Level.Iteration)
public void beforeIteration() throws IOException {
raf = new RandomAccessFile(f, "rw");
offset = 0;
deltaIndex = 0;
}
@TearDown(Level.Iteration)
public void afterIteration() throws IOException {
raf.close();
}
@Benchmark
public void test() throws IOException {
offset = offset + deltas[deltaIndex];
if (offset >= fileSize) {
offset = 0;
}
deltaIndex++;
if (deltaIndex >= deltas.length) {
deltaIndex = 0;
}
raf.seek(offset);
raf.write((byte) offset);
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import org.openjdk.bench.java.io.BlackholedOutputStream;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.infra.Blackhole;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class SerializationWriteReplace {
private BlackholedOutputStream bos;
private ObjectOutputStream os;
@Setup
public void setupStreams(Blackhole bh) throws IOException {
bos = new BlackholedOutputStream(bh);
os = new ObjectOutputStream(bos);
}
@TearDown
public void downStreams() throws IOException {
os.close();
bos.close();
os = null;
bos = null;
}
@Benchmark
public void writeReplace() throws IOException, ClassNotFoundException {
os.writeObject(new Class2());
}
public abstract static class Base implements Serializable {
private static final long serialVersionUID = 1L;
}
public static class Class1 extends Base {
private static final long serialVersionUID = 2L;
}
public static class Class2 extends Class1 {
private static final long serialVersionUID = 3L;
Object writeReplace() throws ObjectStreamException {
return new Class3();
}
}
public static class Class3 extends Base {
private static final long serialVersionUID = 4L;
private String tuto = "tuto";
private byte b = (byte) 0xff;
}
}

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.io;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring UTF8 char operations.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class UTF8 {
private String s;
private BlackholedOutputStream bos;
private DataOutputStream dos;
@Setup
public void setup(Blackhole bh) {
bos = new BlackholedOutputStream(bh);
dos = new DataOutputStream(bos);
s = "abcdefghijklmnopqrstuvxyz0123456789";
}
@Benchmark
public void testCharConversion() throws IOException {
dos.writeUTF(s);
}
}

View File

@ -0,0 +1,180 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring System.arraycopy in different ways.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ArrayCopy {
private static final byte[] TEST_BYTES = "HTTP/1.0".getBytes();
private static final char[] TEST_CHARS = new char[46];
private static final Object[] TEST_OBJECTS = new Object[200]; // Uses a minimum of 160 internal positions for internal copying
// a length which the compiler cannot prove is a constant
public static int nonConstCharLength = TEST_CHARS.length;
public static int nonConstByteLength = TEST_BYTES.length;
public static int nonConstObjectLength = TEST_OBJECTS.length;
// Use this array to copy objects in.
public char[] dummyCharArray = new char[TEST_CHARS.length];
public byte[] dummyByteArray = new byte[TEST_BYTES.length];
public Object[] dummyObjectArray = new Object[TEST_OBJECTS.length];
@Setup
public void setup() {
for (int i = 0; i < TEST_OBJECTS.length; i++) {
TEST_OBJECTS[i] = new Object();
dummyObjectArray[i] = new Object();
}
}
/**
* This test case do the same work as testArrayCopy. We should make sure
* testArrayCopy is equally fast or better. Compare the two and you measure
* the system call versus explicit copy for-loop.
*/
@Benchmark
public void copyLoop() {
for (int j = 0; j < dummyByteArray.length; j++) {
dummyByteArray[j] = TEST_BYTES[j];
}
}
/**
* Test that we can optimize away the code since it should not have any side
* effects
*/
@Benchmark
public void copyLoopLocalArray() {
byte[] localDummyByteArray = new byte[TEST_BYTES.length];
for (int j = 0; j < localDummyByteArray.length; j++) {
localDummyByteArray[j] = TEST_BYTES[j];
}
}
/**
* This test case do the same work as testArrayCopy. We should make sure
* testArrayCopy is equally fast or better. Compare the two and you measure
* the system call versus explicit copy for-loop.
* <p/>
* Uses non-provable constant length.
*/
@Benchmark
public void copyLoopNonConst() {
for (int i = 0; i < nonConstByteLength; i++) {
dummyByteArray[i] = TEST_BYTES[i];
}
}
/**
* This test case do the same work as testCopyLoop. We should make sure
* testArrayCopy is equally fast or better. Compare the two and you measure
* the system call versus explicit copy for-loop.
*/
@Benchmark
public void arrayCopy() {
System.arraycopy(TEST_BYTES, 0, dummyByteArray, 0, dummyByteArray.length);
}
/**
* Test that we can optimize away the code since it should not have any side
* effects
*/
@Benchmark
public void arrayCopyLocalArray() {
byte[] localDummyByteArray = new byte[TEST_BYTES.length];
System.arraycopy(TEST_BYTES, 0, localDummyByteArray, 0, localDummyByteArray.length);
}
/**
* This test case do the same work as testCopyLoop. We should make sure
* testArrayCopy is equally fast or better. Compare the two and you measure
* the system call versus explicit copy for-loop.
* <p/>
* Uses non-provable constant length.
*/
@Benchmark
public void arrayCopyNonConst() {
System.arraycopy(TEST_BYTES, 0, dummyByteArray, 0, nonConstByteLength);
}
@Benchmark
public void arrayCopyChar() {
System.arraycopy(TEST_CHARS, 0, dummyCharArray, 0, dummyCharArray.length);
}
@Benchmark
public void arrayCopyCharNonConst() {
System.arraycopy(TEST_CHARS, 0, dummyCharArray, 0, nonConstCharLength);
}
@Benchmark
public void arrayCopyObject() {
System.arraycopy(TEST_OBJECTS, 0, dummyObjectArray, 0, dummyObjectArray.length);
}
@Benchmark
public void arrayCopyObjectNonConst() {
System.arraycopy(TEST_OBJECTS, 0, dummyObjectArray, 0, nonConstObjectLength);
}
/**
* This test copies inside a object array, that is same source array as dest
* array. Copies backwards in the array.
*/
@Benchmark
@OperationsPerInvocation(40)
public void arrayCopyObjectSameArraysBackward() {
for (int i = 0; i < 40; i++) {
System.arraycopy(dummyObjectArray, i, dummyObjectArray, i + 40, 80);
}
}
/**
* This test copies inside a object array, that is same source array as dest
* array. Copies forward in the array. There is a special version for this
* in JRockit.
*/
@Benchmark
@OperationsPerInvocation(40)
public void arrayCopyObjectSameArraysForward() {
for (int i = 0; i < 40; i++) {
System.arraycopy(dummyObjectArray, i + 40, dummyObjectArray, i, 80);
}
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring aligned System.arraycopy.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ArrayCopyAligned {
@Param({"1", "3", "5", "10", "20", "70", "150", "300", "600", "1200"})
int length;
int fromPos, toPos;
byte[] fromByteArr, toByteArr;
char[] fromCharArr, toCharArr;
int[] fromIntArr, toIntArr;
long[] fromLongArr, toLongArr;
@Setup
public void setup() {
// Both positions aligned
fromPos = 8;
toPos = 8;
fromByteArr = new byte[1210];
toByteArr = new byte[1210];
fromCharArr = new char[1210];
toCharArr = new char[1210];
fromIntArr = new int[1210];
toIntArr = new int[1210];
fromLongArr = new long[1210];
toLongArr = new long[1210];
}
@Benchmark
public void testByte() {
System.arraycopy(fromByteArr, fromPos, toByteArr, toPos, length);
}
@Benchmark
public void testChar() {
System.arraycopy(fromCharArr, fromPos, toCharArr, toPos, length);
}
@Benchmark
public void testInt() {
System.arraycopy(fromIntArr, fromPos, toIntArr, toPos, length);
}
@Benchmark
public void testLong() {
System.arraycopy(fromLongArr, fromPos, toLongArr, toPos, length);
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring Unaligned System.arraycopy.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ArrayCopyUnalignedBoth {
@Param({"1", "3", "5", "10", "20", "70", "150", "300", "600", "1200"})
int length;
int fromPos, toPos;
byte[] fromByteArr, toByteArr;
char[] fromCharArr, toCharArr;
int[] fromIntArr, toIntArr;
long[] fromLongArr, toLongArr;
@Setup
public void setup() {
// Both positions Unaligned
fromPos = 9;
toPos = 10;
fromByteArr = new byte[1210];
toByteArr = new byte[1210];
fromCharArr = new char[1210];
toCharArr = new char[1210];
fromIntArr = new int[1210];
toIntArr = new int[1210];
fromLongArr = new long[1210];
toLongArr = new long[1210];
}
@Benchmark
public void testByte() {
System.arraycopy(fromByteArr, fromPos, toByteArr, toPos, length);
}
@Benchmark
public void testChar() {
System.arraycopy(fromCharArr, fromPos, toCharArr, toPos, length);
}
@Benchmark
public void testInt() {
System.arraycopy(fromIntArr, fromPos, toIntArr, toPos, length);
}
@Benchmark
public void testLong() {
System.arraycopy(fromLongArr, fromPos, toLongArr, toPos, length);
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring Unaligned System.arraycopy.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ArrayCopyUnalignedDst {
@Param({"1", "3", "5", "10", "20", "70", "150", "300", "600", "1200"})
int length;
int fromPos, toPos;
byte[] fromByteArr, toByteArr;
char[] fromCharArr, toCharArr;
int[] fromIntArr, toIntArr;
long[] fromLongArr, toLongArr;
@Setup
public void setup() {
// Dst position Unaligned
fromPos = 8;
toPos = 9;
fromByteArr = new byte[1210];
toByteArr = new byte[1210];
fromCharArr = new char[1210];
toCharArr = new char[1210];
fromIntArr = new int[1210];
toIntArr = new int[1210];
fromLongArr = new long[1210];
toLongArr = new long[1210];
}
@Benchmark
public void testByte() {
System.arraycopy(fromByteArr, fromPos, toByteArr, toPos, length);
}
@Benchmark
public void testChar() {
System.arraycopy(fromCharArr, fromPos, toCharArr, toPos, length);
}
@Benchmark
public void testInt() {
System.arraycopy(fromIntArr, fromPos, toIntArr, toPos, length);
}
@Benchmark
public void testLong() {
System.arraycopy(fromLongArr, fromPos, toLongArr, toPos, length);
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring Unaligned System.arraycopy.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ArrayCopyUnalignedSrc {
@Param({"1", "3", "5", "10", "20", "70", "150", "300", "600", "1200"})
int length;
int fromPos, toPos;
byte[] fromByteArr, toByteArr;
char[] fromCharArr, toCharArr;
int[] fromIntArr, toIntArr;
long[] fromLongArr, toLongArr;
@Setup
public void setup() {
// Dst position Unaligned
fromPos = 5;
toPos = 8;
fromByteArr = new byte[1210];
toByteArr = new byte[1210];
fromCharArr = new char[1210];
toCharArr = new char[1210];
fromIntArr = new int[1210];
toIntArr = new int[1210];
fromLongArr = new long[1210];
toLongArr = new long[1210];
}
@Benchmark
public void testByte() {
System.arraycopy(fromByteArr, fromPos, toByteArr, toPos, length);
}
@Benchmark
public void testChar() {
System.arraycopy(fromCharArr, fromPos, toCharArr, toPos, length);
}
@Benchmark
public void testInt() {
System.arraycopy(fromIntArr, fromPos, toIntArr, toPos, length);
}
@Benchmark
public void testLong() {
System.arraycopy(fromLongArr, fromPos, toLongArr, toPos, length);
}
}

View File

@ -0,0 +1,70 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Tests java.lang.Class.forName() with various inputs.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class ClassForName {
private String aName, bName, cName;
@Setup
public void setup() {
aName = A.class.getName();
bName = B.class.getName();
cName = C.class.getName();
}
/** Calls Class.forName with the same name over and over again. The class asked for exists. */
@Benchmark
public void test1(Blackhole bh) throws ClassNotFoundException {
bh.consume(Class.forName(aName));
}
/** Calls Class.forName with the three different names over and over again. All classes asked for exist. */
@Benchmark
public void test3(Blackhole bh) throws ClassNotFoundException {
bh.consume(Class.forName(aName));
bh.consume(Class.forName(bName));
bh.consume(Class.forName(cName));
}
static class A {}
static class B {}
static class C {}
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.BitSet;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class Clone {
private BitSet testObj1;
private Date testObj2;
private char[] testObj3;
@Setup
public void setup() {
testObj1 = new BitSet(10);
testObj2 = new Date();
testObj3 = new char[5];
}
/** Calls clone on three different types. The types are java.util.BitSet, java.util.Date and char[]. */
@Benchmark
public void cloneThreeDifferent(Blackhole bh) {
bh.consume(testObj1.clone());
bh.consume(testObj2.clone());
bh.consume(testObj3.clone());
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Tests for sun.misc.FloatingDecimal. Performs floating point number to String conversions.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class FloatingDecimal {
private double[] randomArray, twoDecimalsArray, integerArray;
private static final int TESTSIZE = 1000;
@Setup
public void setup() {
Random r = new Random(1123);
randomArray = new double[TESTSIZE];
twoDecimalsArray = new double[TESTSIZE];
integerArray = new double[TESTSIZE];
for (int i = 0; i < TESTSIZE; i++) {
randomArray[i] = r.nextDouble() * 10000.0D;
twoDecimalsArray[i] = ((double) (10000 - r.nextInt(20000))) / 100;
integerArray[i] = (double) (100 - r.nextInt(200));
}
}
/** Tests Double.toString on double values generated from Random.nextDouble() */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void randomDoubleToString(Blackhole bh) {
for (double d : randomArray) {
bh.consume(Double.toString(d));
}
}
/** Tests Double.toString on double values that are integers between -100 and 100. */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void integerDoubleToString(Blackhole bh) {
for (double d : integerArray) {
bh.consume(Double.toString(d));
}
}
/** Tests Double.toString on double values that are between -100 and 100 and have two decimal digits. */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void twoDecimalsDoubleToString(Blackhole bh) {
for (double d : twoDecimalsArray) {
bh.consume(Double.toString(d));
}
}
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
/**
* Tests Thread.getStackTrace()
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class GetStackTrace {
@Benchmark
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public StackTraceElement[] depth0() {
return Thread.currentThread().getStackTrace();
}
@Benchmark
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public StackTraceElement[] depth1() {
return depth0();
}
@Benchmark
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public StackTraceElement[] depth2() {
return depth1();
}
}

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Tests java.lang.Integer
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class Integers {
@Param("500")
private int size;
private String[] strings;
@Setup
public void setup() {
Random r = new Random(0);
strings = new String[size];
for (int i = 0; i < size; i++) {
strings[i] = "" + (r.nextInt(10000) - 5000);
}
}
@Benchmark
public void parseInt(Blackhole bh) {
for (String s : strings) {
bh.consume(Integer.parseInt(s));
}
}
}

View File

@ -0,0 +1,93 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class Longs {
@Param("500")
private int size;
private long[] longArraySmall;
private long[] longArrayBig;
@Setup
public void setup() {
longArraySmall = new long[size];
longArrayBig = new long[size];
for (int i = 0; i < size; i++) {
longArraySmall[i] = 100L * i + i + 103L;
longArrayBig[i] = ((100L * i + i) << 32) + 4543 + i * 4;
}
}
/** Performs toString on a bunch of java.lang.Long:s, all with small values, just a couple of digits. */
@Benchmark
@Threads(Threads.MAX)
public void toStringSmall(Blackhole bh) {
for (long value : longArraySmall) {
bh.consume(Long.toString(value));
}
}
/** Performs toString on a bunch of java.lang.Long:s, all with large values, around 10 digits. */
@Benchmark
@Threads(Threads.MAX)
public void toStringBig(Blackhole bh) {
for (long value : longArrayBig) {
bh.consume(Long.toString(value));
}
}
/*
* Have them public to avoid total unrolling
*/
public int innerLoops = 1500;
@Benchmark
@Threads(Threads.MAX)
public long repetitiveSubtraction() {
long x = 127, dx = 0;
for (int i = 0; i < innerLoops; i++) {
x -= dx;
dx = (dx - x);
}
return x;
}
}

View File

@ -0,0 +1,131 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring java.lang.Class.newInstance speed.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class NewInstance {
public Class<?>[] samePublicClasses;
public Class<?>[] differentPublicClasses;
public Class<?>[] differentPublicClassesConstant;
public Class<?>[] sameProtectedClasses;
public Class<?>[] differentProtectedClasses;
@Setup
public void setup() {
samePublicClasses = new Class<?>[]{Apub.class, Apub.class, Apub.class};
differentPublicClasses = new Class<?>[]{Apub.class, Bpub.class, Cpub.class};
differentPublicClassesConstant = new Class<?>[]{Apub.class, Bpub.class, Cpub.class};
sameProtectedClasses = new Class<?>[]{Apro.class, Apro.class, Apro.class};
differentProtectedClasses = new Class<?>[]{Apro.class, Bpro.class, Cpro.class};
}
/**
* Performs Class.newInstance on the same class over and over again. That it is the same class is not provable at
* compile time. The class is protected.
*/
@Benchmark
public void threeSameProtected(Blackhole bh) throws IllegalAccessException, InstantiationException {
for (Class<?> cl : sameProtectedClasses) {
bh.consume(cl.newInstance());
}
}
/**
* Performs Class.newInstance on three different classes, just allocating one instance of one class at a time. The
* classes are all protected.
*/
@Benchmark
public void threeDifferentProtected(Blackhole bh) throws IllegalAccessException, InstantiationException {
for (Class<?> cl : differentProtectedClasses) {
bh.consume(cl.newInstance());
}
}
/**
* Performs Class.newInstance on the same class over and over again. That it is the same class is not provable at
* compile time. The class is public.
*/
@Benchmark
public void threeSamePublic(Blackhole bh) throws IllegalAccessException, InstantiationException {
for (Class<?> cl : samePublicClasses) {
bh.consume(cl.newInstance());
}
}
/**
* Performs Class.newInstance on three different classes, just allocating one instance of one class at a time. The
* classes are all public.
*/
@Benchmark
public void threeDifferentPublic(Blackhole bh) throws IllegalAccessException, InstantiationException {
for (Class<?> cl : differentPublicClasses) {
bh.consume(cl.newInstance());
}
}
/**
* Performs Class.newInstance on three different classes, just allocating one instance of one class at a time. The
* classes are all public.
*/
@Benchmark
public void threeDifferentPublicConstant(Blackhole bh) throws IllegalAccessException, InstantiationException {
bh.consume(Apub.class.newInstance());
bh.consume(Bpub.class.newInstance());
bh.consume(Cpub.class.newInstance());
}
@Benchmark
public void threeDifferentPublicFinal(Blackhole bh) throws IllegalAccessException, InstantiationException {
for (Class<?> cl : differentPublicClassesConstant) {
bh.consume(cl.newInstance());
}
}
/* Protected test classes */
static class Apro {}
static class Bpro {}
static class Cpro {}
/* Public test classes */
public static class Apub {}
public static class Bpub {}
public static class Cpub {}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
/**
* This benchmark assesses different hashCode strategies in HotSpot
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ObjectHashCode {
@Benchmark
@Fork
public int mode_default() {
return System.identityHashCode(new Object());
}
@Benchmark
@Fork(jvmArgsPrepend = {"-XX:+UnlockExperimentalVMOptions", "-XX:hashCode=0"})
public int mode_0() {
return System.identityHashCode(new Object());
}
@Benchmark
@Fork(jvmArgsPrepend = {"-XX:+UnlockExperimentalVMOptions", "-XX:hashCode=1"})
public int mode_1() {
return System.identityHashCode(new Object());
}
@Benchmark
@Fork(jvmArgsPrepend = {"-XX:+UnlockExperimentalVMOptions", "-XX:hashCode=2"})
public int mode_2() {
return System.identityHashCode(new Object());
}
@Benchmark
@Fork(jvmArgsPrepend = {"-XX:+UnlockExperimentalVMOptions", "-XX:hashCode=3"})
public int mode_3() {
return System.identityHashCode(new Object());
}
@Benchmark
@Fork(jvmArgsPrepend = {"-XX:+UnlockExperimentalVMOptions", "-XX:hashCode=4"})
public int mode_4() {
return System.identityHashCode(new Object());
}
@Benchmark
@Fork(jvmArgsPrepend = {"-XX:+UnlockExperimentalVMOptions", "-XX:hashCode=5"})
public int mode_5() {
return System.identityHashCode(new Object());
}
}

View File

@ -0,0 +1,77 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringBuffers {
private String name;
private String blaha;
private Sigurd sig;
@Setup
public void setup() {
name = "joe";
blaha = "sniglogigloienlitenapasomarengrodasjukadjavelhej";
sig = new Sigurd();
}
@Benchmark
public String appendAndToString() {
return "MyStringBuffer named:" + ((name == null) ? "unknown" : name) + ".";
}
@Benchmark
public String toStringComplex() {
return sig.toString();
}
static class Sigurd {
int x;
byte y;
String z = "yahoo";
@Override
public String toString() {
return Integer.toString(x) + "_" + Integer.toString((int) y) + "_" + z + "_";
}
}
@Benchmark
public String substring() {
return blaha.substring(30, 35);
}
}

View File

@ -0,0 +1,259 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringBuilders {
private String[] strings;
private String[] str3p4p2;
private String[] str16p8p7;
private String[] str3p9p8;
private String[] str22p40p31;
@Setup
public void setup() {
strings = new String[]{"As", "your", "attorney,", "I",
"advise", "you", "to", "drive", "at", "top", "speed", "it'll",
"be", "a", "god", "damn", "miracle", "if", "we", "can", "get",
"there", "before", "you", "turn", "into", "a", "wild", "animal."};
str3p4p2 = new String[]{"123", "1234", "12"};
str16p8p7 = new String[]{"1234567890123456", "12345678", "1234567"};
str3p9p8 = new String[]{"123", "123456789", "12345678"};
str22p40p31 = new String[]{"1234567890123456789012", "1234567890123456789012345678901234567890", "1234567890123456789012345678901"};
}
/** StringBuilder wins over StringMaker. */
@Benchmark
public String concat3p4p2() throws Exception {
return new StringBuilder(String.valueOf(str3p4p2[0])).append(str3p4p2[1]).append(str3p4p2[2]).toString();
}
/** StringBuilder wins over StringMaker. */
@Benchmark
public String concat16p8p7() throws Exception {
return new StringBuilder(String.valueOf(str16p8p7[0])).append(str16p8p7[1]).append(str16p8p7[2]).toString();
}
/** StringMaker wins over StringBuilder since the two last strings causes StringBuilder to do expand. */
@Benchmark
public String concat3p9p8() throws Exception {
return new StringBuilder(String.valueOf(str3p9p8[0])).append(str3p9p8[1]).append(str3p9p8[2]).toString();
}
/** StringMaker wins over StringBuilder. */
@Benchmark
public String concat22p40p31() throws Exception {
return new StringBuilder(String.valueOf(str22p40p31[0])).append(str22p40p31[1]).append(str22p40p31[2]).toString();
}
@Benchmark
public StringBuilder appendLoop8() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; i++) {
sb.append(strings[i]);
}
return sb;
}
@Benchmark
public StringBuilder appendLoop16() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++) {
sb.append(strings[i]);
}
return sb;
}
@Benchmark
public String toStringCharWithChar1() {
StringBuilder result = new StringBuilder();
result.append('a');
return result.toString();
}
@Benchmark
public String toStringCharWithChar2() {
StringBuilder result = new StringBuilder();
result.append('a');
result.append('p');
return result.toString();
}
@Benchmark
public String toStringCharWithChar4() {
StringBuilder result = new StringBuilder();
result.append('a');
result.append('p');
result.append('a');
result.append(' ');
return result.toString();
}
@Benchmark
public String toStringCharWithChar8() {
StringBuilder result = new StringBuilder();
result.append('a');
result.append('p');
result.append('a');
result.append(' ');
result.append('a');
result.append('p');
result.append('a');
result.append(' ');
return result.toString();
}
@Benchmark
public String toStringCharWithChar16() {
StringBuilder result = new StringBuilder();
result.append('a');
result.append('b');
result.append('c');
result.append('d');
result.append('e');
result.append('f');
result.append('g');
result.append('h');
result.append('i');
result.append('j');
result.append('k');
result.append('l');
result.append('m');
result.append('n');
result.append('o');
result.append('p');
return result.toString();
}
@Benchmark
public String toStringCharWithString8() {
StringBuilder result = new StringBuilder();
result.append("a");
result.append("b");
result.append("c");
result.append("d");
result.append("e");
result.append("f");
result.append("g");
result.append("h");
return result.toString();
}
@Benchmark
public String toStringCharWithString16() {
StringBuilder result = new StringBuilder();
result.append("a");
result.append("b");
result.append("c");
result.append("d");
result.append("e");
result.append("f");
result.append("g");
result.append("h");
result.append("i");
result.append("j");
result.append("k");
result.append("l");
result.append("m");
result.append("n");
result.append("o");
result.append("p");
return result.toString();
}
@Benchmark
public String toStringCharWithInt8() {
StringBuilder result = new StringBuilder();
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
return result.toString();
}
@Benchmark
public String toStringCharWithBool8() {
StringBuilder result = new StringBuilder();
result.append(true);
result.append(false);
result.append(true);
result.append(true);
result.append(false);
result.append(true);
result.append(false);
result.append(false);
return result.toString();
}
@Benchmark
public String toStringCharWithFloat8() {
StringBuilder result = new StringBuilder();
result.append(113.110F);
result.append(156456.36435637F);
result.append(65436434.64632F);
result.append(42654634.64540F);
result.append(63464351.64537F);
result.append(634564.645711F);
result.append(64547.64311F);
result.append(4763456341.64531F);
return result.toString();
}
@Benchmark
public String toStringCharWithMixed8() {
StringBuilder result = new StringBuilder();
result.append('a');
result.append("stringelinglinglinglong");
result.append('a');
result.append("stringelinglinglinglong");
result.append('a');
result.append("stringelinglinglinglong");
result.append('p');
result.append("stringelinglinglinglong");
return result.toString();
}
}

View File

@ -0,0 +1,100 @@
/*
* Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Trivial String concatenation benchmark.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringConcat {
public int intValue = 4711;
public String stringValue = String.valueOf(intValue);
public Object objectValue = Long.valueOf(intValue);
public boolean boolValue = true;
public byte byteValue = (byte)-128;
@Benchmark
public String concatConstInt() {
return "string" + intValue;
}
@Benchmark
public String concatConstString() {
return "string" + stringValue;
}
@Benchmark
public String concatConstIntConstInt() {
return "string" + intValue + "string" + intValue;
}
@Benchmark
public String concatConstStringConstInt() {
return "string" + stringValue + "string" + intValue;
}
@Benchmark
public String concatConst4String() {
return "string" + stringValue + stringValue + stringValue + stringValue;
}
@Benchmark
public String concatConst2String() {
return "string" + stringValue + stringValue;
}
@Benchmark
public String concatConstBoolByte() {
return "string" + boolValue + byteValue;
}
@Benchmark
public String concatConst6String() {
return "string" + stringValue + stringValue + stringValue + stringValue + stringValue + stringValue;
}
@Benchmark
public String concatConst6Object() {
return "string" + objectValue + objectValue + objectValue + objectValue + objectValue + objectValue;
}
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
/**
* Performance test of String.hashCode() function
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringHashCode {
private String hashcode;
private String hashcode0;
@Setup
public void setup() {
hashcode = "abcdefghijkl";
hashcode0 = new String(new char[]{72, 90, 100, 89, 105, 2, 72, 90, 100, 89, 105, 2});
}
/**
* Benchmark testing String.hashCode() with a regular 12 char string with
* the result possibly cached in String
*/
@Benchmark
public int cached() {
return hashcode.hashCode();
}
/**
* Benchmark testing String.hashCode() with a 12 char string with the
* hashcode = 0 forcing the value to always be recalculated.
*/
@Benchmark
public int notCached() {
return hashcode0.hashCode();
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringHttp {
private byte[] httpRequest;
private String[] httpResponse;
private byte[] buf;
@Setup
public void setup() {
buf = new byte[4080];
httpRequest = "GET /foo/bar/baz HTTP/1.1\nHost: foo.com\n".getBytes();
httpResponse = new String[]{"Date: 4/20/2003 10:21:31", "Last-Modified: 4/15/2003 10:21:31",
"Content-Length: 1234", "", "foo bar baz foo bar baz foo bar baz foo bar baz foo bar baz",
"foo bar baz foo bar baz foo bar baz foo bar baz foo bar baz",
"foo bar baz foo bar baz foo bar baz foo bar baz foo bar baz",
"foo bar baz foo bar baz foo bar baz foo bar baz foo bar baz",
"foo bar baz foo bar baz foo bar baz foo bar baz foo bar baz"};
}
@Benchmark
public void parseRequest(Blackhole bh) {
bh.consume(new String(httpRequest, 0, 3));
bh.consume(new String(httpRequest, 5, 11));
bh.consume(new String(httpRequest, 17, 8));
bh.consume(new String(httpRequest, 32, 7));
}
@Benchmark
public int bufferResponse() {
int pos = 0;
int n = httpResponse.length;
for (String s : httpResponse) {
byte[] b = s.getBytes();
int len = b.length;
System.arraycopy(b, 0, buf, pos, len);
pos += len;
buf[pos++] = '\n';
}
return n;
}
}

View File

@ -0,0 +1,138 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringIndexOf {
private String dataString;
private String searchString;
private String dataStringBig;
private String searchStringBig;
private String data;
private String sub;
private String shortSub1;
private String data2;
private String shortSub2;
@Setup
public void setup() {
dataString = "ngdfilsoscargfdgf";
searchString = "oscar";
dataStringBig = "2937489745890797905764956790452976742965790437698498409583479067ngdcapaapapapasdkajdlkajskldjaslkjdlkasjdsalkjas";
searchStringBig = "capaapapapasdkajdlkajskldjaslkjdlkasjdsalk";
data = "0000100101010010110101010010101110101001110110101010010101010010000010111010101010101010100010010101110111010101101010100010010100001010111111100001010101001010100001010101001010101010111010010101010101010101010101010";
sub = "10101010";
shortSub1 = "1";
data2 = "00001001010100a10110101010010101110101001110110101010010101010010000010111010101010101010a100010010101110111010101101010100010010a100a0010101111111000010101010010101000010101010010101010101110a10010101010101010101010101010";
shortSub2 = "a";
}
/** IndexOf Micros Strings */
/**
* Benchmarks String.indexOf with a rather small String to search and a rather small String to search for. The
* searched string contains the string that is searched for.
*/
@Benchmark
public int success() {
return dataString.indexOf(searchString, 2);
}
/**
* Benchmarks String.indexOf with a rather big String to search and a rather big String to search for. The searched
* string contains the string that is searched for.
*/
@Benchmark
public int successBig() {
return dataStringBig.indexOf(searchStringBig, 2);
}
/**
* Benchmarks String.indexOf with a rather big String. Search repeatedly for a matched that is 8 chars and most
* oftenly will require a inner lopp match in String.indexOf with sse42.
*/
@Benchmark
public int advancedWithMediumSub() {
int index = 0;
int dummy = 0;
while ((index = data.indexOf(sub, index)) > -1) {
index++;
dummy += index;
}
return dummy;
}
/**
* Benchmarks String.indexOf with a rather big String. Search repeatedly for a matched that is 1 chars will find a
* huge amount of matches
*/
@Benchmark
public int advancedWithShortSub1() {
int dummy = 0;
int index = 0;
while ((index = data.indexOf(shortSub1, index)) > -1) {
index++;
dummy += index;
}
return dummy;
}
/**
* Benchmarks String.indexOf with a rather big String. Search repeatedly for a matched that is 1 chars but only with
* a few matches.
*/
@Benchmark
public int advancedWithShortSub2() {
int dummy = 0;
int index = 0;
while ((index = data2.indexOf(shortSub2, index)) > -1) {
index++;
dummy += index;
}
return dummy;
}
@Benchmark
public void constantPattern() {
String tmp = "simple-hash:SHA-1/UTF-8";
if (!tmp.contains("SHA-1")) {
throw new RuntimeException("indexOf failed");
}
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringOther {
private String testString;
private Random rnd;
private String str1, str2, str3, str4;
@Setup
public void setup() {
testString = "Idealism is what precedes experience; cynicism is what follows.";
str1 = "vm-guld vm-guld vm-guld";
str2 = "vm-guld vm-guld vm-guldx";
str3 = "vm-guld vm-guld vm-guldx";
str4 = "adadaskasdjierudks";
rnd = new Random();
}
@Benchmark
public void charAt(Blackhole bh) {
for (int i = 0; i < testString.length(); i++) {
bh.consume(testString.charAt(i));
}
}
@Benchmark
public int compareTo() {
int total = 0;
total += str1.compareTo(str2);
total += str2.compareTo(str3);
total += str3.compareTo(str4);
return total;
}
/**
* Creates (hopefully) unique Strings and internizes them, creating a zillion forgettable strings in the JVMs string
* pool.
* <p/>
* This will test 1.) The data structure/whatever for getting and adding Strings to intern table. 2.) The
* intern-caches (java) behaviour on negative lookup (the string is new) 3.) GC's handling of weak handles. Since
* every gc we must process and pretty much kill a zillion interned strings that are now not referenced anymore, the
* majority of GC time will be spent in handle processing. So we get a picture of how well the pathological case of
* this goes.
*/
@Benchmark
public String internUnique() {
return String.valueOf(rnd.nextInt()).intern();
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class StringUpperLower {
private String strLowerCase;
private String strMixedCase;
private String strUpperCase;
@Setup
public void setup() {
strLowerCase = "this is a simple string with different cases";
strMixedCase = "This IS a SImpLE strING wITh DiFfErEnT CASeS";
strUpperCase = "THIS IS A SIMPLE STRING WITH DIFFERENT CASES";
}
@Benchmark
public String lowerToLower() {
return strLowerCase.toLowerCase();
}
@Benchmark
public String mixedToLower() {
return strMixedCase.toLowerCase();
}
@Benchmark
public String upperToLower() {
return strUpperCase.toLowerCase();
}
@Benchmark
public String lowerToUpper() {
return strLowerCase.toUpperCase();
}
@Benchmark
public String mixedToUpper() {
return strMixedCase.toUpperCase();
}
@Benchmark
public String upperToUpper() {
return strUpperCase.toUpperCase();
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class Systems {
@Benchmark
public long currentTimeMillis() {
return System.currentTimeMillis();
}
@Benchmark
public long nanoTime() {
return System.nanoTime();
}
}

View File

@ -0,0 +1,97 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.util.concurrent.TimeUnit;
/**
* Test to launch and gather threads. Measure time for different parts.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
public class ThreadStartJoin {
private static final int THREADS = Runtime.getRuntime().availableProcessors();
private Thread[] ts;
@Benchmark
public void test() throws InterruptedException {
ts = new TestThread[THREADS];
for (int i = 0; i < THREADS; i++) {
ts[i] = new TestThread();
}
for (int i = 0; i < THREADS; i++) {
ts[i].start();
}
for (Thread mythread : ts) {
mythread.join();
if (mythread.isAlive()) {
throw new IllegalStateException("Couldn't join in time in LPHhello.");
}
}
}
@TearDown
public final void cleanup() {
if (ts != null) {
for (Thread t : ts) {
if (t != null) {
t.interrupt();
}
}
ts = null;
}
}
static final class TestThread extends Thread {
private static int num = 0;
public TestThread() {
super(TestThread.name());
}
private synchronized static String name() {
return "TestThread-" + num++;
}
public void run() {
// do nothing
}
}
}

View File

@ -0,0 +1,208 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.lang.invoke.VolatileCallSite;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This benchmark evaluates INDY performance under dynamic target updates.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class CallSiteSetTarget {
/*
* Implementation notes:
* - This test makes sense for mutable and volatile call sites only
* - Multiple threads are calling the same callsite, and invalidator thread tries to swap target on the fly.
* - Additional baseline includes "raw" test, calling callsite's MH directly
*/
private static volatile CallSite cs;
private static MethodHandle doCall1;
private static MethodHandle doCall2;
static {
try {
doCall1 = MethodHandles.lookup().findVirtual(CallSiteSetTarget.class, "call1", MethodType.methodType(int.class));
doCall2 = MethodHandles.lookup().findVirtual(CallSiteSetTarget.class, "call2", MethodType.methodType(int.class));
cs = new MutableCallSite(doCall1);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private int i1;
private int i2;
public int call1() {
return i1++;
}
public int call2() {
return i2++;
}
@Benchmark
public int baselineRaw() throws Throwable {
return (int) cs.getTarget().invokeExact(this);
}
@Benchmark
public int testMutable() throws Throwable {
return (int) INDY_Mutable().invokeExact(this);
}
@Benchmark
public int testVolatile() throws Throwable {
return (int) INDY_Volatile().invokeExact(this);
}
/* =========================== INDY TRAMPOLINES ============================== */
private static MethodType MT_bsm() {
shouldNotCallThis();
return MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class);
}
private static MethodHandle MH_bsm_Mutable() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Mutable", MT_bsm());
}
private static MethodHandle MH_bsm_Volatile() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Volatile", MT_bsm());
}
private static MethodHandle INDY_Mutable() throws Throwable {
shouldNotCallThis();
return ((CallSite) MH_bsm_Mutable().invoke(MethodHandles.lookup(), "doCall1", MethodType.methodType(int.class, CallSiteSetTarget.class))).dynamicInvoker();
}
private static MethodHandle INDY_Volatile() throws Throwable {
shouldNotCallThis();
return ((CallSite) MH_bsm_Volatile().invoke(MethodHandles.lookup(), "doCall1", MethodType.methodType(int.class, CallSiteSetTarget.class))).dynamicInvoker();
}
public static CallSite bsm_Mutable(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteSetTarget.class) {
if (cs == null)
cs = new MutableCallSite(doCall1);
return cs;
}
}
public static CallSite bsm_Volatile(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteSetTarget.class) {
if (cs == null)
cs = new VolatileCallSite(doCall1);
return cs;
}
}
private static void shouldNotCallThis() {
// if this gets called, the transformation has not taken place
throw new AssertionError("this code should be statically transformed away by Indify");
}
/* =========================== INVALIDATE LOGIC ============================== */
private final static Invalidator invalidator = new Invalidator();
@Setup
public void setup() {
invalidator.start();
}
@TearDown
public void tearDown() throws InterruptedException {
invalidator.stop();
}
public static class Invalidator implements Runnable {
private final long period = Integer.getInteger("period", 1000);
private final AtomicBoolean started = new AtomicBoolean();
private volatile Thread thread;
@Override
public void run() {
try {
while(!Thread.interrupted()) {
if (cs != null) {
cs.setTarget(doCall1);
}
TimeUnit.MICROSECONDS.sleep(period);
if (cs != null) {
cs.setTarget(doCall2);
}
TimeUnit.MICROSECONDS.sleep(period);
}
} catch (InterruptedException e) {
// do nothing
}
}
public void start() {
if (started.compareAndSet(false, true)) {
thread = new Thread(this);
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
}
public void stop() {
if (thread != null) {
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
started.set(false);
}
}
}
}

View File

@ -0,0 +1,149 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.lang.invoke.VolatileCallSite;
import java.util.concurrent.TimeUnit;
/**
* This benchmark evaluates INDY performance under dynamic target updates.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class CallSiteSetTargetSelf {
/*
* Implementation notes:
* - This test makes sense for mutable and volatile call sites only
* - Multiple threads are calling the same callsite, and each call is swapping the target.
* - Additional baseline includes "raw" test, calling callsite's MH directly
*
* - NOTE: invalidating shared target callsite is very bad with multiple threads.
* I.e. this test is inherently non-scalable.
*/
private static CallSite cs;
private static MethodHandle doCall1;
private static MethodHandle doCall2;
static {
try {
doCall1 = MethodHandles.lookup().findVirtual(CallSiteSetTargetSelf.class, "call1", MethodType.methodType(int.class));
doCall2 = MethodHandles.lookup().findVirtual(CallSiteSetTargetSelf.class, "call2", MethodType.methodType(int.class));
cs = new MutableCallSite(doCall1);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private int i1;
private int i2;
public int call1() {
cs.setTarget(doCall2);
return i1++;
}
public int call2() {
cs.setTarget(doCall1);
return i2++;
}
@Benchmark
public int baselineRaw() throws Throwable {
return (int) cs.getTarget().invokeExact(this);
}
@Benchmark
public int testMutable() throws Throwable {
return (int) INDY_Mutable().invokeExact(this);
}
@Benchmark
public int testVolatile() throws Throwable {
return (int) INDY_Volatile().invokeExact(this);
}
/* =========================== INDY TRAMPOLINES ============================== */
private static MethodType MT_bsm() {
shouldNotCallThis();
return MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class);
}
private static MethodHandle MH_bsm_Mutable() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Mutable", MT_bsm());
}
private static MethodHandle MH_bsm_Volatile() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Volatile", MT_bsm());
}
private static MethodHandle INDY_Mutable() throws Throwable {
shouldNotCallThis();
return ((CallSite) MH_bsm_Mutable().invoke(MethodHandles.lookup(), "doCall1", MethodType.methodType(int.class, CallSiteSetTargetSelf.class))).dynamicInvoker();
}
private static MethodHandle INDY_Volatile() throws Throwable {
shouldNotCallThis();
return ((CallSite) MH_bsm_Volatile().invoke(MethodHandles.lookup(), "doCall1", MethodType.methodType(int.class, CallSiteSetTargetSelf.class))).dynamicInvoker();
}
public static CallSite bsm_Mutable(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteSetTarget.class) {
if (cs == null)
cs = new MutableCallSite(doCall1);
return cs;
}
}
public static CallSite bsm_Volatile(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteSetTarget.class) {
if (cs == null)
cs = new VolatileCallSite(doCall1);
return cs;
}
}
private static void shouldNotCallThis() {
// if this gets called, the transformation has not taken place
throw new AssertionError("this code should be statically transformed away by Indify");
}
}

View File

@ -0,0 +1,165 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.lang.invoke.VolatileCallSite;
import java.util.concurrent.TimeUnit;
/**
* This benchmark evaluates INDY performance when call sites are not changed.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class CallSiteStable {
/*
* Implementation notes:
* - Test is calling simple method via INDY
* - Additional baseline includes "raw" test, calling target method directly in virtual and static modes
*/
private static java.lang.invoke.CallSite cs;
private static MethodHandle doCallMH;
static {
try {
doCallMH = MethodHandles.lookup().findVirtual(CallSiteStable.class, "doCall", MethodType.methodType(int.class, int.class));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private int i;
public int doCall(int value) {
return value + 1;
}
public static int doCallStatic(int value) {
return value + 1;
}
@Benchmark
public void baselineVirtual() {
i = doCall(i);
}
@Benchmark
public void baselineStatic() {
i = doCallStatic(i);
}
@Benchmark
public void testConstant() throws Throwable {
i = (int) INDY_Constant().invokeExact(this, i);
}
@Benchmark
public void testMutable() throws Throwable {
i = (int) INDY_Mutable().invokeExact(this, i);
}
@Benchmark
public void testVolatile() throws Throwable {
i = (int) INDY_Volatile().invokeExact(this, i);
}
/* =========================== INDY TRAMPOLINES ============================== */
private static MethodType MT_bsm() {
shouldNotCallThis();
return MethodType.methodType(java.lang.invoke.CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class);
}
private static MethodHandle MH_bsm_Constant() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Constant", MT_bsm());
}
private static MethodHandle MH_bsm_Mutable() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Mutable", MT_bsm());
}
private static MethodHandle MH_bsm_Volatile() throws ReflectiveOperationException {
shouldNotCallThis();
return MethodHandles.lookup().findStatic(MethodHandles.lookup().lookupClass(), "bsm_Volatile", MT_bsm());
}
private static MethodHandle INDY_Constant() throws Throwable {
shouldNotCallThis();
return ((java.lang.invoke.CallSite) MH_bsm_Constant().invoke(MethodHandles.lookup(), "doCall", MethodType.methodType(int.class, CallSiteStable.class, int.class))).dynamicInvoker();
}
private static MethodHandle INDY_Mutable() throws Throwable {
shouldNotCallThis();
return ((java.lang.invoke.CallSite) MH_bsm_Mutable().invoke(MethodHandles.lookup(), "doCall", MethodType.methodType(int.class, CallSiteStable.class, int.class))).dynamicInvoker();
}
private static MethodHandle INDY_Volatile() throws Throwable {
shouldNotCallThis();
return ((java.lang.invoke.CallSite) MH_bsm_Volatile().invoke(MethodHandles.lookup(), "doCall", MethodType.methodType(int.class, CallSiteStable.class, int.class))).dynamicInvoker();
}
public static java.lang.invoke.CallSite bsm_Constant(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteStable.class) {
if (cs == null)
cs = new ConstantCallSite(doCallMH);
return cs;
}
}
public static java.lang.invoke.CallSite bsm_Mutable(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteStable.class) {
if (cs == null)
cs = new MutableCallSite(doCallMH);
return cs;
}
}
public static java.lang.invoke.CallSite bsm_Volatile(MethodHandles.Lookup lookup, String name, MethodType type) {
synchronized (CallSiteStable.class) {
if (cs == null)
cs = new VolatileCallSite(doCallMH);
return cs;
}
}
private static void shouldNotCallThis() {
// if this gets called, the transformation has not taken place
throw new AssertionError("this code should be statically transformed away by Indify");
}
}

View File

@ -0,0 +1,94 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.lookup/publicLookup() acquiring performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class LookupAcquire {
/*
Implementation notes:
- this test assesses acquiring lookup object only
- baseline includes returning cached lookup object, i.e. measures infra overheads
- additional baseline includes allocating object to understand Lookup instantiation costs
- cached instance is static, because that provides (unbeatably) best performance
*/
public static MethodHandles.Lookup cached;
@Setup
public void setup() {
cached = MethodHandles.lookup();
}
@Benchmark
public MethodHandles.Lookup baselineCached() throws Exception {
return cached;
}
@Benchmark
public MyLookup baselineNew() throws Exception {
return new MyLookup(Object.class, 1);
}
@Benchmark
public MethodHandles.Lookup testPublicLookup() throws Exception {
return MethodHandles.publicLookup();
}
@Benchmark
public MethodHandles.Lookup testLookup() throws Exception {
return MethodHandles.lookup();
}
/**
* Dummy Lookup-looking class.
* Lookup is final, and all constructors are private.
* This class mocks the hotpath.
*/
private static class MyLookup {
private final Class<?> klass;
private final int mode;
public MyLookup(Class<?> klass, int i) {
this.klass = klass;
this.mode = i;
}
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandle.lookup() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class LookupDefaultFind {
/*
Implementation notes:
- does not test findSpecial, since the privileges of this Bench is not enough to access private members
*/
@Benchmark
public MethodHandle testConstructor() throws Exception {
return MethodHandles.lookup().findConstructor(Victim.class, MethodType.methodType(void.class));
}
@Benchmark
public MethodHandle testGetter() throws Exception {
return MethodHandles.lookup().findGetter(Victim.class, "field", int.class);
}
@Benchmark
public MethodHandle testSetter() throws Exception {
return MethodHandles.lookup().findSetter(Victim.class, "field", int.class);
}
@Benchmark
public MethodHandle testStatic() throws Exception {
return MethodHandles.lookup().findStatic(Victim.class, "staticWork", MethodType.methodType(int.class));
}
@Benchmark
public MethodHandle testStaticGetter() throws Exception {
return MethodHandles.lookup().findStaticGetter(Victim.class, "staticField", int.class);
}
@Benchmark
public MethodHandle testStaticSetter() throws Exception {
return MethodHandles.lookup().findStaticSetter(Victim.class, "staticField", int.class);
}
@Benchmark
public MethodHandle testVirtual() throws Exception {
return MethodHandles.lookup().findVirtual(Victim.class, "virtualWork", MethodType.methodType(int.class));
}
public static class Victim {
public static int staticField;
public int field;
public Victim() {
// do nothing
}
public int virtualWork() {
return 1;
}
public static int staticWork() {
return 1;
}
private int specialWork() {
return 1;
}
}
}

View File

@ -0,0 +1,106 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandle.publicLookup() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class LookupPublicFind {
/*
Implementation notes:
- findSpecial is not tested, unable to do this with public lookup object
*/
@Benchmark
public MethodHandle testConstructor() throws Exception {
return MethodHandles.publicLookup().findConstructor(Victim.class, MethodType.methodType(void.class));
}
@Benchmark
public MethodHandle testGetter() throws Exception {
return MethodHandles.publicLookup().findGetter(Victim.class, "field", int.class);
}
@Benchmark
public MethodHandle testSetter() throws Exception {
return MethodHandles.publicLookup().findSetter(Victim.class, "field", int.class);
}
@Benchmark
public MethodHandle testStatic() throws Exception {
return MethodHandles.publicLookup().findStatic(Victim.class, "staticWork", MethodType.methodType(int.class));
}
@Benchmark
public MethodHandle testStaticGetter() throws Exception {
return MethodHandles.publicLookup().findStaticGetter(Victim.class, "staticField", int.class);
}
@Benchmark
public MethodHandle testStaticSetter() throws Exception {
return MethodHandles.publicLookup().findStaticSetter(Victim.class, "staticField", int.class);
}
@Benchmark
public MethodHandle testVirtual() throws Exception {
return MethodHandles.publicLookup().findVirtual(Victim.class, "virtualWork", MethodType.methodType(int.class));
}
public static class Victim {
public static int staticField;
public int field;
public Victim() {
// do nothing
}
public int virtualWork() {
return 1;
}
public static int staticWork() {
return 1;
}
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Microbenchmark assesses MethodHandle.asCollector() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleAsCollector {
/*
* Implementation notes:
* - simple array-parameter method is being called
* - baselineRaw calls method directly with dynamically instantiating the array
* - baselineCached calls method directly with pre-cached array
* - additional testCreate() test harnesses the collector acquisition performance
* - testCollector() can be faster than both baselines: it can wrapping array at all
*/
public int i;
private static MethodHandle mh;
private static MethodHandle collectorMH;
private static int[] cachedArgs;
@Setup
public void setup() throws IllegalAccessException, NoSuchMethodException {
mh = MethodHandles.lookup().findVirtual(MethodHandleAsCollector.class, "doWork", MethodType.methodType(void.class, int[].class));
collectorMH = mh.asCollector(int[].class, 5);
cachedArgs = new int[]{1, 2, 3, 4, 5};
}
@Benchmark
public void baselineMH() throws Throwable {
mh.invokeExact(this, new int[] { 1, 2, 3, 4, 5 });
}
@Benchmark
public void baselineMHCached() throws Throwable {
mh.invokeExact(this, cachedArgs);
}
@Benchmark
public void baselineRaw() throws Throwable {
doWork(new int[] { 1, 2, 3, 4, 5});
}
@Benchmark
public void baselineRawCached() throws Throwable {
doWork(cachedArgs);
}
@Benchmark
public MethodHandle testCreate() {
return mh.asCollector(int[].class, 5);
}
@Benchmark
public void testCollector() throws Throwable {
collectorMH.invokeExact(this, 1, 2, 3, 4, 5);
}
public void doWork(int[] args) {
for (int a : args) {
i += a;
}
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Microbenchmark assesses MethodHandle.asSpreader() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleAsSpreader {
/*
* Implementation notes:
* - simple array-parameter method is being called
* - baselineRaw calls method directly with dynamically instantiating the array
* - baselineCached calls method directly with pre-cached array
* - additional testCreate() test harnesses the collector acquisition performance
* - testCollector() can be faster than both baselines: it can wrapping array at all
*/
public int i;
private static MethodHandle mh;
private static MethodHandle spreaderMH;
private static int[] cachedArgs;
@Setup
public void setup() throws IllegalAccessException, NoSuchMethodException {
mh = MethodHandles.lookup().findVirtual(MethodHandleAsSpreader.class, "doWork", MethodType.methodType(void.class, int.class, int.class, int.class, int.class, int.class));
spreaderMH = mh.asSpreader(int[].class, 5);
cachedArgs = new int[]{1, 2, 3, 4, 5};
}
@Benchmark
public void baselineMH() throws Throwable {
mh.invokeExact(this, 1, 2, 3, 4, 5);
}
@Benchmark
public void baselineRaw() throws Throwable {
doWork(1, 2, 3, 4, 5);
}
@Benchmark
public MethodHandle testCreate() {
return mh.asSpreader(int[].class, 5);
}
@Benchmark
public void testSpreader() throws Throwable {
spreaderMH.invokeExact(this, new int[] { 1, 2, 3, 4, 5 });
}
@Benchmark
public void testSpreaderCached() throws Throwable {
spreaderMH.invokeExact(this, cachedArgs);
}
public void doWork(int arg1, int arg2, int arg3, int arg4, int arg5) {
i += (arg1 + arg2 + arg3 + arg4 + arg5);
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Microbenchmark assesses MethodHandle.asVarargCollector() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleAsVarargsCollector {
/*
* Implementation notes:
* - simple array-parameter method is being called
* - baselineRaw calls method directly with dynamically instantiating the array
* - baselineCached calls method directly with pre-cached array
* - additional testCreate() test harnesses the collector acquisition performance
* - testCollector() can be faster than both baselines: it can wrapping array at all
*/
public int i;
private static MethodHandle mh;
private static MethodHandle collectorMH;
private static int[] cachedArgs;
@Setup
public void setup() throws IllegalAccessException, NoSuchMethodException {
mh = MethodHandles.lookup().findVirtual(MethodHandleAsVarargsCollector.class, "doWork", MethodType.methodType(void.class, int[].class));
collectorMH = mh.asVarargsCollector(int[].class);
cachedArgs = new int[]{1, 2, 3, 4, 5};
}
@Benchmark
public void baselineMH() throws Throwable {
mh.invoke(this, new int[] { 1, 2, 3, 4, 5 });
}
@Benchmark
public void baselineMHCached() throws Throwable {
mh.invoke(this, cachedArgs);
}
@Benchmark
public void baselineRaw() throws Throwable {
doWork(1, 2, 3, 4, 5);
}
@Benchmark
public void baselineRawCached() throws Throwable {
doWork(cachedArgs);
}
@Benchmark
public MethodHandle testCreate() {
return mh.asVarargsCollector(int[].class);
}
@Benchmark
public void testCollector() throws Throwable {
collectorMH.invoke(this, 1, 2, 3, 4, 5);
}
public void doWork(int... args) {
for (int a : args) {
i += a;
}
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* Benchmark to assess basic MethodHandle performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleBasicInvoke {
/*
* Implementation notes:
* - this is a very basic test, does not do any parameter conversion (in fact, no parameters at all)
* - baselines include calling method directly, and doing the same via reflection
* - baselineRaw is known to be super-fast with good inlining
*/
private int i;
private static MethodHandle mh;
private static Method ref;
private static MethodHandle mhUnreflect;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findVirtual(MethodHandleBasicInvoke.class, "doWork", MethodType.methodType(int.class));
ref = MethodHandleBasicInvoke.class.getMethod("doWork");
ref.setAccessible(true);
mhUnreflect = MethodHandles.lookup().unreflect(ref);
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork();
}
@Benchmark
public int baselineReflect() throws Throwable {
return (int) ref.invoke(this);
}
@Benchmark
public int testMH_Plain_Invoke() throws Throwable {
return (int) mh.invoke(this);
}
@Benchmark
public int testMH_Plain_Exact() throws Throwable {
return (int) mh.invokeExact(this);
}
@Benchmark
public int testMH_Unreflect_Invoke() throws Throwable {
return (int) mhUnreflect.invoke(this);
}
@Benchmark
public int testMH_Unreflect_Exact() throws Throwable {
return (int) mhUnreflect.invokeExact(this);
}
public int doWork() {
return i++;
}
}

View File

@ -0,0 +1,93 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandle.bindTo() binding performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleBindToBinding {
/*
Implementation notes:
- calls static method to avoid binding "this"
- tests binding costs with multiple depth (C1, C2, C3)
- baseline includes naive side effect store
- lowering the binding cost will minimise both the spread between C1/C2/C3 and difference towards baseline
- this test performance will never reach the baseline
*/
private MethodHandle mhOrig;
@Setup
public void setup() throws Throwable {
mhOrig = MethodHandles.lookup().findStatic(MethodHandleBindToBinding.class, "doWork",
MethodType.methodType(Integer.class, Integer.class, Integer.class, Integer.class));
}
@Benchmark
public Object baselineRaw() {
return mhOrig;
}
@Benchmark
public Object testBind_C1() throws Throwable {
MethodHandle mhCurry1 = mhOrig.bindTo(1);
return mhCurry1;
}
@Benchmark
public Object testBind_C2() throws Throwable {
MethodHandle mhCurry1 = mhOrig.bindTo(1);
MethodHandle mhCurry2 = mhCurry1.bindTo(2);
return mhCurry2;
}
@Benchmark
public Object testBind_C3() throws Throwable {
MethodHandle mhCurry1 = mhOrig.bindTo(1);
MethodHandle mhCurry2 = mhCurry1.bindTo(2);
MethodHandle mhCurry3 = mhCurry2.bindTo(3);
return mhCurry3;
}
public static Integer doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses currying with MethodHandle.bindTo() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleBindToCurry {
/*
Implementation notes:
- calls static method to avoid binding "this"
- tests the performance of gradually curried methods, hoping for compiler to optimize
- arguments are volatile, to break optimistic CSE happening before the actual call
- using invokeExact and Integers to skip argument conversions
- baseline includes calling the method directly, and this is known to be super-fast due to inlining
*/
private MethodHandle mhOrig;
private MethodHandle mhCurry1;
private MethodHandle mhCurry2;
private MethodHandle mhCurry3;
private volatile Integer arg1 = 1;
private volatile Integer arg2 = 2;
private volatile Integer arg3 = 3;
@Setup
public void setup() throws Throwable {
mhOrig = MethodHandles.lookup().findStatic(MethodHandleBindToCurry.class, "doWork",
MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class));
mhCurry1 = mhOrig.bindTo(arg1);
mhCurry2 = mhCurry1.bindTo(arg2);
mhCurry3 = mhCurry2.bindTo(arg3);
}
@Benchmark
public int baselineRaw() {
return doWork(arg1, arg2, arg3);
}
@Benchmark
public int testInvoke_C0() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoke_C1() throws Throwable {
return (int) mhCurry1.invokeExact(arg2, arg3);
}
@Benchmark
public int testInvoke_C2() throws Throwable {
return (int) mhCurry2.invokeExact(arg3);
}
@Benchmark
public int testInvoke_C3() throws Throwable {
return (int) mhCurry3.invokeExact();
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,99 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks autoboxing conversion.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertBoxing {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling static method as to minimize virtual dispatch overheads.
*/
private Integer valueBoxed;
private int valueUnboxed;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findStatic(MethodHandleConvertBoxing.class, "target", MethodType.methodType(int.class, int.class));
newType = MethodType.methodType(int.class, Integer.class);
valueBoxed = 42;
valueUnboxed = 42;
}
@Benchmark
public int baselineExact() throws Throwable {
return (int) mh.invokeExact(valueUnboxed);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(int.class, Integer.class));
}
@Benchmark
public int test_3_Call() throws Throwable {
return (int) mh.invoke(valueBoxed);
}
public static int target(int value) {
return value + 1;
}
}

View File

@ -0,0 +1,101 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks the casts are applied.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertCast {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling static method as to minimize virtual dispatch overheads.
*/
private A instanceA;
private B instanceB;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findStatic(MethodHandleConvertCast.class, "target", MethodType.methodType(A.class, A.class));
newType = MethodType.methodType(A.class, B.class);
instanceA = new A();
instanceB = new B();
}
@Benchmark
public A baselineExact() throws Throwable {
return (A) mh.invokeExact(instanceA);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(A.class, B.class));
}
@Benchmark
public A test_3_Call() throws Throwable {
return (A) mh.invoke(instanceB);
}
public static A target(A value) {
return value;
}
public static class A {}
public static class B extends A { }
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks the return type conversion: void -> int.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertReturnPrimitive {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling virtual method to guarantee side-effects on value, without trading off scalability.
* This test should be executed in non-shared mode.
*/
public int value;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findVirtual(MethodHandleConvertReturnPrimitive.class, "target", MethodType.methodType(void.class));
newType = MethodType.methodType(int.class, MethodHandleConvertReturnPrimitive.class);
}
@Benchmark
public void baselineExact() throws Throwable {
mh.invokeExact(this);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(int.class, MethodHandleConvertReturnPrimitive.class));
}
@Benchmark
public int test_3_Call() throws Throwable {
return (int) mh.invoke(this);
}
public void target() {
value++;
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks the return type conversion: void -> Integer.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertReturnReference {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling virtual method to guarantee side-effects on value, without trading off scalability.
* This test should be executed in non-shared mode.
*/
public int value;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findVirtual(MethodHandleConvertReturnReference.class, "target", MethodType.methodType(void.class));
newType = MethodType.methodType(Integer.class, MethodHandleConvertReturnReference.class);
}
@Benchmark
public void baselineExact() throws Throwable {
mh.invokeExact(this);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(Integer.class, MethodHandleConvertReturnReference.class));
}
@Benchmark
public Object test_3_Call() throws Throwable {
return mh.invoke(this);
}
public void target() {
value++;
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks the return type conversion: int -> void.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertReturnVoid {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling virtual method to guarantee side-effects on value, without trading off scalability.
* This test should be executed in non-shared mode.
*/
public int value;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findVirtual(MethodHandleConvertReturnVoid.class, "target", MethodType.methodType(int.class));
newType = MethodType.methodType(void.class, MethodHandleConvertReturnVoid.class);
}
@Benchmark
public int baselineExact() throws Throwable {
return (int) mh.invokeExact(this);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(void.class, MethodHandleConvertReturnVoid.class));
}
@Benchmark
public void test_3_Call() throws Throwable {
mh.invoke(this);
}
public int target() {
return value++;
}
}

View File

@ -0,0 +1,98 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks the unboxing conversion.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertUnboxing {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling static method as to minimize virtual dispatch overheads.
*/
private Integer valueBoxed;
private int valueUnboxed;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findStatic(MethodHandleConvertUnboxing.class, "target", MethodType.methodType(int.class, Integer.class));
newType = MethodType.methodType(int.class, int.class);
valueBoxed = 42;
valueUnboxed = 42;
}
@Benchmark
public int baselineExact() throws Throwable {
return (int) mh.invokeExact(valueBoxed);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(int.class, int.class));
}
@Benchmark
public int test_3_Call() throws Throwable {
return (int) mh.invoke(valueUnboxed);
}
public static int target(Integer value) {
return value + 1;
}
}

View File

@ -0,0 +1,98 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses runtime argument conversion performance for MethodHandles.
* This particular test checks the widening conversion.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleConvertWidening {
/*
* Implementation notes:
*
* Baseline is invokeExact call, which presumably measures the performance without argument conversion.
*
* The test is subdivided into three subtests, gradually doing more work:
* - 1_Convert: calls MH.asType to do actual conversion
* - 2_MTConvert: instantiates MT, and then calls MH.asType to do actual conversion
* - 3_Call: calls MH.invoke, requesting argument conversion
*
* Calling static method as to minimize virtual dispatch overheads.
*/
private long valueLong;
private int valueInt;
private MethodHandle mh;
private MethodType newType;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findStatic(MethodHandleConvertWidening.class, "target", MethodType.methodType(long.class, long.class));
newType = MethodType.methodType(long.class, int.class);
valueInt = 42;
valueLong = 42L;
}
@Benchmark
public long baselineExact() throws Throwable {
return (long) mh.invokeExact(valueLong);
}
@Benchmark
public MethodHandle test_1_Convert() throws Throwable {
return mh.asType(newType);
}
@Benchmark
public MethodHandle test_2_MTConvert() throws Throwable {
return mh.asType(MethodType.methodType(long.class, int.class));
}
@Benchmark
public long test_3_Call() throws Throwable {
return (long) mh.invoke(valueInt);
}
public static long target(long value) {
return value + 1;
}
}

View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark to assess basic MethodHandle performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleInvokeWithArgs {
/*
* Implementation notes:
* - this is a very basic test, does not do any parameter conversion (in fact, no parameters at all)
* - baselines include calling method directly, and doing the same via reflection
* - baselineRaw is known to be super-fast with good inlining
*/
private int i;
private static MethodHandle mh;
private Integer a = 42;
@Setup
public void setup() throws Throwable {
mh = MethodHandles.lookup().findVirtual(MethodHandleInvokeWithArgs.class, "doWork", MethodType.methodType(int.class, Integer.class));
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork(a);
}
@Benchmark
public int baselineInvoke() throws Throwable {
return (int) mh.invoke(this, a);
}
@Benchmark
public int baselineInvokeExact() throws Throwable {
return (int) mh.invokeExact(this, a);
}
@Benchmark
public int testInvoke_WithArguments() throws Throwable {
return (int) mh.invokeWithArguments(this, a);
}
public int doWork(Integer a) {
return i += a;
}
}

View File

@ -0,0 +1,118 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark evaluates the performance of MethodHandleProxies.*
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleProxiesAsIFInstance {
/**
* Implementation notes:
* - asInterfaceInstance() can only target static MethodHandle (adapters needed to call instance method?)
* - baselineCompute will quickly degrade to GC test, if escape analysis is unable to spare the allocation
* - testCreate* will always be slower if allocation is not eliminated; baselineAllocCompute makes sure allocation is present
*/
public int i;
private MethodHandle target;
private Doable precreated;
@Setup
public void setup() throws Throwable {
target = MethodHandles.lookup().findStatic(MethodHandleProxiesAsIFInstance.class, "doWork", MethodType.methodType(int.class, int.class));
precreated = MethodHandleProxies.asInterfaceInstance(Doable.class, target);
}
@Benchmark
public Doable testCreate() {
Doable doable = MethodHandleProxies.asInterfaceInstance(Doable.class, target);
return doable; // make sure allocation happens
}
@Benchmark
public Doable testCreateCall() {
Doable doable = MethodHandleProxies.asInterfaceInstance(Doable.class, target);
i = doable.doWork(i); // make sure computation happens
return null; // let allocation be eliminated
}
@Benchmark
public Doable testCall() {
i = precreated.doWork(i); // make sure computation happens
return precreated;
}
@Benchmark
public Doable baselineCompute() {
Doable doable = new Doable() {
@Override
public int doWork(int i) {
return MethodHandleProxiesAsIFInstance.doWork(i);
}
};
i = doable.doWork(i); // make sure computation happens
return null; // let allocation be eliminated
}
@Benchmark
public Doable baselineAllocCompute() {
Doable doable = new Doable() {
@Override
public int doWork(int i) {
return MethodHandleProxiesAsIFInstance.doWork(i);
}
};
i = doable.doWork(i); // make sure computation happens
return doable; // make sure allocation happens
}
public static int doWork(int i) {
return i + 1;
}
public interface Doable {
int doWork(int i);
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark evaluates the performance of MethodHandleProxies.* supplementary methods.
*
* @author Aleksey Shipilev (aleksey.shipilev@oracle.com)
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandleProxiesSuppl {
/*
* Implementation notes:
* - This is a very naive test, evaluates the performance of service methods.
*/
private Doable instance;
@Setup
public void setup() throws Throwable {
MethodHandle target = MethodHandles.lookup().findStatic(MethodHandleProxiesSuppl.class, "doWork", MethodType.methodType(int.class, int.class));
instance = MethodHandleProxies.asInterfaceInstance(Doable.class, target);
}
@Benchmark
public Object baselineReturn() {
return instance;
}
@Benchmark
public boolean testIsWrapperInstance() {
return MethodHandleProxies.isWrapperInstance(instance);
}
@Benchmark
public Class<?> testInstanceType() {
return MethodHandleProxies.wrapperInstanceType(instance);
}
@Benchmark
public MethodHandle testInstanceTarget() {
return MethodHandleProxies.wrapperInstanceTarget(instance);
}
public static int doWork(int i) {
throw new IllegalStateException("Can't touch this");
}
public interface Doable {
int doWork(int i);
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the performance of MethodHandles.arrayElementGetter
*
* @author Aleksey Shipilev (aleksey.shipilev@oracle.com)
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandlesArrayElementGetter {
/**
* Implementation notes:
* - creating simple array, and accessing the middle element
* - might have done iteration over array, but that will measure pipelining effects instead
* - volatile modifier on array breaks the DCE, which would otherwise eliminate the array load
* - the rationale for array size and access pattern is coherent to SetterBench
*/
private static final int SIZE = 1024;
private static final int POS = SIZE/2;
private static MethodHandle mh;
private volatile int[] array;
@Setup
public void setup() throws Throwable {
array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
mh = MethodHandles.arrayElementGetter(int[].class);
}
@Benchmark
public MethodHandle testCreate() {
return MethodHandles.arrayElementGetter(int[].class);
}
@Benchmark
public int baselineRaw() {
return access(array, POS);
}
@Benchmark
public int testGetter() throws Throwable {
return (int) mh.invoke(array, POS);
}
public int access(int[] array, int pos) {
return array[pos];
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the performance of MethodHandles.arrayElementSetter
*
* @author Aleksey Shipilev (aleksey.shipilev@oracle.com)
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandlesArrayElementSetter {
/**
* Implementation notes:
* - creating simple array, and accessing the middle element
* - might have done iteration over array, but that will measure pipelining effects instead
* - volatile modifier on array breaks the DCE, which would otherwise eliminate the array store
* - the array is not shared to prevent true sharing
* - the array is large enough to prevent false sharing
*/
private static final int SIZE = 1024;
private static final int POS = SIZE/2;
private static MethodHandle mh;
private volatile int[] array;
@Setup
public void setup() throws Throwable {
array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
mh = MethodHandles.arrayElementSetter(int[].class);
}
@Benchmark
public MethodHandle testCreate() {
return MethodHandles.arrayElementSetter(int[].class);
}
@Benchmark
public void baselineRaw() {
access(array, POS, 1);
}
@Benchmark
public void testSetter() throws Throwable {
mh.invoke(array, POS, 1);
}
public void access(int[] array, int pos, int v) {
array[pos] = v;
}
}

View File

@ -0,0 +1,126 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.catchException() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandlesCatchException {
/**
* Implementation notes:
* - emulating instance method handles because of current issue with instance methods
* - exception is cached to harness the MH code, not exception instantiation
* - measuring two modes:
* a) always going through normal code path;
* b) always going through exceptional one
* - baselines do the same thing in pure Java
*/
private static final MyException MY_EXCEPTION = new MyException();
private int i1;
private int i2;
private static MethodHandle methNormal;
private static MethodHandle methExceptional;
@Setup
public void setup() throws Throwable {
MethodHandle bodyNormal = MethodHandles.lookup()
.findStatic(MethodHandlesCatchException.class, "doWorkNormal",
MethodType.methodType(void.class, MethodHandlesCatchException.class));
MethodHandle bodyExceptional = MethodHandles.lookup()
.findStatic(MethodHandlesCatchException.class, "doWorkExceptional",
MethodType.methodType(void.class, MethodHandlesCatchException.class));
MethodHandle fallback = MethodHandles.lookup()
.findStatic(MethodHandlesCatchException.class, "fallback",
MethodType.methodType(void.class, MyException.class, MethodHandlesCatchException.class));
methNormal = MethodHandles.catchException(bodyNormal, MyException.class, fallback);
methExceptional = MethodHandles.catchException(bodyExceptional, MyException.class, fallback);
}
@Benchmark
public void baselineNormal() {
try {
doWorkNormal(this);
} catch (MyException e) {
fallback(e, this);
}
}
@Benchmark
public void baselineExceptional() {
try {
doWorkExceptional(this);
} catch (MyException e) {
fallback(e, this);
}
}
@Benchmark
public void testNormal() throws Throwable {
methNormal.invokeExact(this);
}
@Benchmark
public void testExceptional() throws Throwable {
methExceptional.invokeExact(this);
}
public static void doWorkNormal(MethodHandlesCatchException inst) throws MyException {
inst.i1++;
}
public static void doWorkExceptional(MethodHandlesCatchException inst) throws MyException {
inst.i1++;
throw MY_EXCEPTION;
}
public static void fallback(MyException ex, MethodHandlesCatchException inst) {
inst.i2++;
}
public static class MyException extends Exception {
}
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.constant() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesConstant {
private MethodHandle mh;
private Integer cachedInt;
@Setup
public void setup() {
cachedInt = 42;
mh = MethodHandles.constant(Integer.class, 42);
}
@Benchmark
public Integer baselineReturn() {
return cachedInt;
}
@Benchmark
public MethodHandle interCreate() throws Throwable {
return MethodHandles.constant(Integer.class, 42);
}
@Benchmark
public MethodHandle interCreateCached() throws Throwable {
return MethodHandles.constant(Integer.class, cachedInt);
}
@Benchmark
public Integer testInvoke() throws Throwable {
return (Integer) mh.invoke();
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.dropArguments() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesDropArguments {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
*/
private MethodHandle orig;
private MethodHandle modified;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
orig = MethodHandles.lookup().findStatic(MethodHandlesDropArguments.class, "doWork", MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class));
modified = MethodHandles.dropArguments(orig, 0, int.class);
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork(arg1, arg2, arg3);
}
@Benchmark
public int baselineMH() throws Throwable {
return (int) orig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoke() throws Throwable {
return (int) modified.invokeExact(0, arg1, arg2, arg3);
}
@Benchmark
public MethodHandle interCreate() throws Throwable {
return MethodHandles.dropArguments(orig, 0, int.class);
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.exactInvoker() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesExactInvoker {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
* - tested method should perform no worse than the baseline
*/
private MethodHandle mhOrig;
private MethodHandle mnInvoke;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
MethodType mt = MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class);
mhOrig = MethodHandles.lookup().findStatic(MethodHandlesInsertArguments.class, "doWork", mt);
mnInvoke = MethodHandles.exactInvoker(mt);
}
@Benchmark
public int baselineOrig() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoker() throws Throwable {
return (int) mnInvoke.invokeExact(mhOrig, arg1, arg2, arg3);
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.filterArguments() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesFilterArgs {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
* - the filter is empty to measure infra costs, not the filter itself
* - baselines should be comparable for each method if optimized enough
*/
private MethodHandle orig;
private MethodHandle modified1;
private MethodHandle modified2;
private MethodHandle modified3;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
orig = MethodHandles.lookup().findStatic(MethodHandlesFilterArgs.class, "doWork", MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class));
MethodHandle filter = MethodHandles.lookup().findStatic(MethodHandlesFilterArgs.class, "filter", MethodType.methodType(Integer.class, Integer.class));
modified1 = MethodHandles.filterArguments(orig, 0, filter);
modified2 = MethodHandles.filterArguments(orig, 0, filter, filter);
modified3 = MethodHandles.filterArguments(orig, 0, filter, filter, filter);
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork(arg1, arg2, arg3);
}
@Benchmark
public int baselineRawConvert() throws Throwable {
return doWork(filter(arg1), filter(arg2), filter(arg3));
}
@Benchmark
public int baselineMH() throws Throwable {
return (int) orig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int baselineMHConvert() throws Throwable {
return (int) orig.invokeExact(filter(arg1), filter(arg2), filter(arg3));
}
@Benchmark
public int testInvoke_M1() throws Throwable {
return (int) modified1.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoke_M2() throws Throwable {
return (int) modified2.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoke_M3() throws Throwable {
return (int) modified3.invokeExact(arg1, arg2, arg3);
}
public static Integer filter(Integer a) {
return a;
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.filterReturnValue() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesFilterReturn {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
*/
private MethodHandle orig;
private MethodHandle filter;
private MethodHandle modified;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
orig = MethodHandles.lookup().findStatic(MethodHandlesFilterReturn.class, "doWork", MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class));
filter = MethodHandles.lookup().findStatic(MethodHandlesFilterReturn.class, "filter", MethodType.methodType(int.class, int.class));
modified = MethodHandles.filterReturnValue(orig, filter);
}
@Benchmark
public int baselineRaw() throws Throwable {
return filter(doWork(arg1, arg2, arg3));
}
@Benchmark
public int baselineMH() throws Throwable {
return filter((int) orig.invokeExact(arg1, arg2, arg3));
}
@Benchmark
public int testInvoke() throws Throwable {
return (int) modified.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public MethodHandle interCreate() throws Throwable {
return MethodHandles.filterReturnValue(orig, filter);
}
public static int filter(int a) {
return a * 2;
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.foldArguments() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesFoldArguments {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
*/
private MethodHandle mhOrig;
private MethodHandle mhFolded;
private MethodHandle mhTarget;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
mhOrig = MethodHandles.lookup().findStatic(MethodHandlesFoldArguments.class, "doWork", MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class));
mhFolded = MethodHandles.lookup().findStatic(MethodHandlesFoldArguments.class, "doWork", MethodType.methodType(int.class, int.class, Integer.class, Integer.class, Integer.class));
mhTarget = MethodHandles.foldArguments(mhFolded, mhOrig);
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork(arg1, arg2, arg3);
}
@Benchmark
public int invoke_Raw() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int invoke_Folded() throws Throwable {
return (int) mhFolded.invokeExact(0, arg1, arg2, arg3);
}
@Benchmark
public int invoke_Target() throws Throwable {
return (int) mhTarget.invokeExact(arg1, arg2, arg3);
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
public static int doWork(int r, Integer a, Integer b, Integer c) {
return r;
}
}

View File

@ -0,0 +1,98 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.guardWithTest() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodHandlesGuardWithTest {
/**
* Implementation notes:
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
* - tested method should perform no worse than the baseline
*/
private MethodHandle mhWork1;
private MethodHandle mhWork2;
private MethodHandle guard;
private boolean choice;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
MethodType mt = MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class);
mhWork1 = MethodHandles.lookup().findVirtual(MethodHandlesGuardWithTest.class, "doWork1", mt);
mhWork2 = MethodHandles.lookup().findVirtual(MethodHandlesGuardWithTest.class, "doWork2", mt);
MethodHandle chooser = MethodHandles.lookup().findVirtual(MethodHandlesGuardWithTest.class, "chooser", MethodType.methodType(boolean.class));
guard = MethodHandles.guardWithTest(chooser, mhWork1, mhWork2);
}
@Benchmark
public int baselineManual() throws Throwable {
if (choice) {
return (int) mhWork1.invokeExact(this, arg1, arg2, arg3);
} else {
return (int) mhWork2.invokeExact(this, arg1, arg2, arg3);
}
}
@Benchmark
public int testInvoke() throws Throwable {
return (int) guard.invoke(this, arg1, arg2, arg3);
}
public boolean chooser() {
choice = !choice;
return choice;
}
public int doWork1(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
public int doWork2(Integer a, Integer b, Integer c) {
return 31*(31*(31*c + b) + a);
}
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.identity() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesIdentity {
private MethodHandle mh;
private Object cachedArg;
@Setup
public void setup() {
cachedArg = new Object();
mh = MethodHandles.identity(Object.class);
}
@Benchmark
public Object baselineRaw() throws Throwable {
return new Object();
}
@Benchmark
public Object baselineRawCached() throws Throwable {
return cachedArg;
}
@Benchmark
public Object testInvoke() throws Throwable {
return mh.invoke(new Object());
}
@Benchmark
public Object testInvokeCached() throws Throwable {
return mh.invoke(cachedArg);
}
}

View File

@ -0,0 +1,100 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.insertArguments() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesInsertArguments {
/**
* Implementation notes:
* - this test is similar to MethodHandleBindToCurryBench
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
*/
private MethodHandle mhOrig;
private MethodHandle mhCurry1;
private MethodHandle mhCurry2;
private MethodHandle mhCurry3;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
mhOrig = MethodHandles.lookup().findStatic(MethodHandlesInsertArguments.class, "doWork", MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class));
mhCurry1 = MethodHandles.insertArguments(mhOrig, 0, arg1);
mhCurry2 = MethodHandles.insertArguments(mhOrig, 0, arg1, arg2);
mhCurry3 = MethodHandles.insertArguments(mhOrig, 0, arg1, arg2, arg3);
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork(arg1, arg2, arg3);
}
@Benchmark
public int invoke_C0() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int invoke_C1() throws Throwable {
return (int) mhCurry1.invokeExact(arg2, arg3);
}
@Benchmark
public int invoke_C2() throws Throwable {
return (int) mhCurry2.invokeExact(arg3);
}
@Benchmark
public int invoke_C3() throws Throwable {
return (int) mhCurry3.invokeExact();
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.invoker() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesInvoker {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
* - tested method should perform no worse than the baseline
*/
private MethodHandle mhOrig;
private MethodHandle mnInvoke;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
MethodType mt = MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class);
mhOrig = MethodHandles.lookup().findStatic(MethodHandlesInsertArguments.class, "doWork", mt);
mnInvoke = MethodHandles.invoker(mt);
}
@Benchmark
public int baselineOrig() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoker() throws Throwable {
return (int) mnInvoke.invokeExact(mhOrig, arg1, arg2, arg3);
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,100 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.permuteArguments() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesPermuteArguments {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
*/
private MethodHandle mhOrig;
private MethodHandle mhNoReorder;
private MethodHandle mhReverse;
private MethodHandle mhShift;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
@Setup
public void setup() throws Throwable {
MethodType mt = MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class);
mhOrig = MethodHandles.lookup().findStatic(MethodHandlesPermuteArguments.class, "doWork", mt);
mhNoReorder = MethodHandles.permuteArguments(mhOrig, mt, 0, 1, 2);
mhReverse = MethodHandles.permuteArguments(mhOrig, mt, 2, 1, 0);
mhShift = MethodHandles.permuteArguments(mhOrig, mt, 2, 0, 1);
}
@Benchmark
public int baselineRaw() throws Throwable {
return doWork(arg1, arg2, arg3);
}
@Benchmark
public int invoke_Raw() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int invoke_NoReorder() throws Throwable {
return (int) mhNoReorder.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int invoke_Reverse() throws Throwable {
return (int) mhReverse.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int invoke_Shift() throws Throwable {
return (int) mhShift.invokeExact(arg1, arg2, arg3);
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.spreadInvoker() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesSpreadInvoker {
/**
* Implementation notes:
* - calling static method to have consistent arg list without receiver type
* - using volatile ints as arguments to prevent opportunistic optimizations
* - using Integers to limit argument conversion costs
* - tested method should perform no worse than the baseline
*/
private MethodHandle mhOrig;
private MethodHandle mnInvoke;
private volatile Integer arg1 = 42;
private volatile Integer arg2 = 43;
private volatile Integer arg3 = 44;
private Object[] cachedArgs;
@Setup
public void setup() throws Throwable {
cachedArgs = new Integer[]{arg1, arg2, arg3};
MethodType mt = MethodType.methodType(int.class, Integer.class, Integer.class, Integer.class);
mhOrig = MethodHandles.lookup().findStatic(MethodHandlesInsertArguments.class, "doWork", mt);
mnInvoke = MethodHandles.spreadInvoker(mt, 0);
}
@Benchmark
public int baselineOrig() throws Throwable {
return (int) mhOrig.invokeExact(arg1, arg2, arg3);
}
@Benchmark
public int testInvoker() throws Throwable {
return (int) mnInvoke.invokeExact(mhOrig, new Object[] { arg1, arg2, arg3 });
}
@Benchmark
public int testInvokerCached() throws Throwable {
return (int) mnInvoke.invokeExact(mhOrig, cachedArgs);
}
public static int doWork(Integer a, Integer b, Integer c) {
return 31*(31*(31*a + b) + c);
}
}

View File

@ -0,0 +1,113 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses MethodHandles.throwException() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodHandlesThrowException {
/**
* Implementation notes:
* - exceptions have a thorough call back to benchmark instance to prevent elimination (against dumb JITs)
* - testing in plain and cached modes
* - baselines do the same thing, but in pure Java
*/
public int flag;
private MethodHandle mh;
private MyException cachedException;
@Setup
public void setup() {
flag = 42;
cachedException = new MyException();
mh = MethodHandles.throwException(void.class, MyException.class);
}
@Benchmark
public int baselineRaw() {
try {
throw new MyException();
} catch (MyException my) {
return my.getFlag();
}
}
@Benchmark
public int baselineRawCached() {
try {
throw cachedException;
} catch (MyException my) {
return my.getFlag();
}
}
@Benchmark
public int testInvoke() throws Throwable {
try {
mh.invoke(new MyException());
throw new IllegalStateException("Should throw exception");
} catch (MyException my) {
return my.getFlag();
}
}
@Benchmark
public int testInvokeCached() throws Throwable {
try {
mh.invoke(cachedException);
throw new IllegalStateException("Should throw exception");
} catch (MyException my) {
return my.getFlag();
}
}
@Benchmark
public MethodHandle interCreate() {
return MethodHandles.throwException(void.class, MyException.class);
}
public class MyException extends Exception {
public int getFlag() {
return flag;
}
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Assesses general MethodType performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeAcquire {
private MethodType pTypes;
@Setup
public void setup() {
pTypes = MethodType.methodType(A.class, B.class);
}
@Benchmark
public MethodType baselineRaw() {
return pTypes;
}
@Benchmark
public MethodType testReturnVoid() {
return MethodType.methodType(void.class);
}
@Benchmark
public MethodType testReturnInt() {
return MethodType.methodType(int.class);
}
@Benchmark
public MethodType testReturnObject() {
return MethodType.methodType(Object.class);
}
@Benchmark
public MethodType testSinglePType() {
return MethodType.methodType(void.class, int.class);
}
@Benchmark
public MethodType testMultiPType() {
return MethodType.methodType(void.class, A.class, B.class);
}
@Benchmark
public MethodType testMultiPType_Arg() {
return MethodType.methodType(void.class, pTypes);
}
public static class A {}
public static class B {}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the MethodType.appendParameterTypes()
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeAppendParams {
/**
* Implementation notes:
* - tests multiple cases, gradually appending more arguments
* - baselines include just returning the same method type, and calling with empty argument list
*/
private MethodType mt;
@Setup
public void setup() {
mt = MethodType.methodType(void.class, int.class);
}
@Benchmark
public MethodType baselineRaw() {
return mt;
}
@Benchmark
public MethodType baselineNop() {
return mt.appendParameterTypes();
}
@Benchmark
public MethodType test_A1() {
return mt.appendParameterTypes(int.class);
}
@Benchmark
public MethodType test_A2() {
return mt.appendParameterTypes(int.class, int.class);
}
@Benchmark
public MethodType test_A3() {
return mt.appendParameterTypes(int.class, int.class, int.class);
}
}

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the MethodType.changeParameterType()
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeChangeParam {
private MethodType mt;
@Setup
public void setup() {
mt = MethodType.methodType(void.class, int.class, int.class);
}
@Benchmark
public MethodType baselineRaw() {
return mt;
}
@Benchmark
public MethodType baselineSame() {
return mt.changeParameterType(1, int.class);
}
@Benchmark
public MethodType testChangeType() {
return mt.changeParameterType(1, Integer.class);
}
}

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the MethodType.changeReturnType()
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeChangeReturn {
private MethodType mt;
@Setup
public void setup() {
mt = MethodType.methodType(void.class, int.class, int.class);
}
@Benchmark
public MethodType baselineRaw() {
return mt;
}
@Benchmark
public MethodType baselineSame() {
return mt.changeReturnType(void.class);
}
@Benchmark
public MethodType testChange() {
return mt.changeReturnType(Integer.class);
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the MethodType.dropParameterTypes()
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeDropParams {
private MethodType mt;
@Setup
public void setup() {
mt = MethodType.methodType(void.class, int.class, int.class, int.class);
}
@Benchmark
public MethodType baselineRaw() {
return mt;
}
@Benchmark
public MethodType baselineSame() {
return mt.dropParameterTypes(0, 0);
}
@Benchmark
public MethodType testDrop_A1() {
return mt.dropParameterTypes(0, 1);
}
@Benchmark
public MethodType testDrop_A2() {
return mt.dropParameterTypes(0, 2);
}
@Benchmark
public MethodType testDrop_A3() {
return mt.dropParameterTypes(0, 3);
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the MethodType.erase() performance
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeGenerify {
private MethodType mt;
@Setup
public void setup() {
mt = MethodType.methodType(void.class, int.class, Integer.class);
}
@Benchmark
public MethodType baselineRaw() {
return mt;
}
@Benchmark
public MethodType testGeneric() {
return mt.generic();
}
@Benchmark
public MethodType testWrapErase() {
return mt.wrap().erase();
}
@Benchmark
public MethodType testErase() {
return mt.erase();
}
@Benchmark
public MethodType testWrap() {
return mt.wrap();
}
@Benchmark
public MethodType testUnwrap() {
return mt.unwrap();
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.MethodType;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assesses the MethodType.insertParameterTypes()
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class MethodTypeInsertParams {
private MethodType mt;
@Setup
public void setup() {
mt = MethodType.methodType(void.class, int.class);
}
@Benchmark
public MethodType baselineRaw() {
return mt;
}
@Benchmark
public MethodType baselineSame() {
return mt.insertParameterTypes(0);
}
@Benchmark
public MethodType testInsert_A1() {
return mt.insertParameterTypes(0, int.class);
}
@Benchmark
public MethodType testInsert_A2() {
return mt.insertParameterTypes(0, int.class, int.class);
}
@Benchmark
public MethodType testInsert_A3() {
return mt.insertParameterTypes(0, int.class, int.class, int.class);
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.lang.invoke.SwitchPoint;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assessing SwitchPoint performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class SwitchPointAdhoc {
/*
* Implementation notes:
* - this test asserts SwitchPoint performance in both valid and invalid cases
* - this test does not assert invalidation performance (hard to do with irreversible SwitchPoint)
* - raw baseline gives the idea for MethodHandle invocation cost
* - CS baseline gives the idea for additional dereference cost
*/
private MethodHandle body1, body2;
private int i;
private java.lang.invoke.SwitchPoint sw1, sw2;
private CallSite cs;
@Setup
public void setup() throws NoSuchMethodException, IllegalAccessException {
sw1 = new java.lang.invoke.SwitchPoint();
sw2 = new java.lang.invoke.SwitchPoint();
SwitchPoint.invalidateAll(new SwitchPoint[]{sw2});
body1 = MethodHandles.lookup().findVirtual(SwitchPointAdhoc.class, "body1", MethodType.methodType(int.class, int.class));
body2 = MethodHandles.lookup().findVirtual(SwitchPointAdhoc.class, "body2", MethodType.methodType(int.class, int.class));
cs = new MutableCallSite(body1);
}
@Benchmark
public void baselineRaw() throws Throwable {
i = (int) body1.invoke(this, i);
}
@Benchmark
public void baselineCS() throws Throwable {
i = (int) cs.getTarget().invoke(this, i);
}
@Benchmark
public void testValid() throws Throwable {
MethodHandle handle = sw1.guardWithTest(body1, body2);
i = (int) handle.invoke(this, i);
}
@Benchmark
public void testInvalid() throws Throwable {
MethodHandle handle = sw2.guardWithTest(body1, body2);
i = (int) handle.invoke(this, i);
}
public int body1(int i) {
return i + 1;
}
public int body2(int i) {
return i + 1;
}
}

View File

@ -0,0 +1,99 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.invoke;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.invoke.*;
import java.util.concurrent.TimeUnit;
/**
* Benchmark assessing SwitchPoint performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class SwitchPointGuard {
/*
* Implementation notes:
* - this test asserts SwitchPoint performance in both valid and invalid cases
* - this test does not assert invalidation performance (hard to do with irreversible SwitchPoint)
* - raw baseline gives the idea for MethodHandle invocation cost
* - CS baseline gives the idea for additional dereference cost
*/
private MethodHandle body1, body2;
private int i;
private SwitchPoint sw1, sw2;
private CallSite cs;
private MethodHandle guard1, guard2;
@Setup
public void setup() throws NoSuchMethodException, IllegalAccessException {
sw1 = new SwitchPoint();
sw2 = new SwitchPoint();
SwitchPoint.invalidateAll(new SwitchPoint[]{sw2});
body1 = MethodHandles.lookup().findVirtual(SwitchPointGuard.class, "body1", MethodType.methodType(int.class, int.class));
body2 = MethodHandles.lookup().findVirtual(SwitchPointGuard.class, "body2", MethodType.methodType(int.class, int.class));
guard1 = sw1.guardWithTest(body1, body2);
guard2 = sw2.guardWithTest(body1, body2);
cs = new MutableCallSite(body1);
}
@Benchmark
public void baselineRaw() throws Throwable {
i = (int) body1.invoke(this, i);
}
@Benchmark
public void baselineCS() throws Throwable {
i = (int) cs.getTarget().invoke(this, i);
}
@Benchmark
public void testValid() throws Throwable {
i = (int) guard1.invoke(this, i);
}
@Benchmark
public void testInvalid() throws Throwable {
i = (int) guard2.invoke(this, i);
}
public int body1(int i) {
return i + 1;
}
public int body2(int i) {
return i + 1;
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class Clazz {
/**
* Get constructor for this class through reflection
*
* @return
* @throws NoSuchMethodException
*/
@Benchmark
public Constructor getConstructor() throws NoSuchMethodException {
return Clazz.class.getConstructor();
}
/**
* Get constructor for the String class through reflection, forcing full
* security check
*
* @return
* @throws NoSuchMethodException
*/
@Benchmark
public Constructor getConstructorDifferentClassLoader() throws NoSuchMethodException {
return String.class.getConstructor();
}
/**
* Get the toString method through reflection on Clazz
*
* @return
*/
@Benchmark
public Method getMethod() throws NoSuchMethodException {
return Clazz.class.getMethod("toString");
}
/**
* Get the toString method through reflection on String, forcing full
* security check
*
* @return
* @throws NoSuchMethodException
*/
@Benchmark
public Method getMethodDifferentClassLoader() throws NoSuchMethodException {
return String.class.getMethod("toString");
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.reflect;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.security.Policy;
import java.security.URIParameter;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* Reflection benchmark
*
* @author sfriberg
*/
@State(Scope.Benchmark)
public class ClazzWithSecurityManager extends Clazz {
@Setup
public void setup() throws IOException, NoSuchAlgorithmException, URISyntaxException {
URI policyFile = ClazzWithSecurityManager.class.getResource("/jmh-security.policy").toURI();
Policy.setPolicy(Policy.getInstance("JavaPolicy", new URIParameter(policyFile)));
System.setSecurityManager(new SecurityManager());
}
}

View File

@ -0,0 +1,114 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.lang.reflect;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.CompilerControl;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring java.lang.reflect.Method.invoke speed.
* <p/>
* TODO: Add tests for virtual and interface methods.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class MethodInvoke {
private Method staticMeth_0;
private Method staticMeth_6ref;
private Method staticMeth_6prim;
private Object[] args_0;
private Object[] args_6ref;
private Object[] args_6prim;
@Setup
public void setup() {
args_0 = new Object[]{};
args_6ref = new Object[]{ new Object(), new Object(),
new Object(), new Object(), new Object(), new Object()};
args_6prim = new Object[]{
new Integer(1), new Long(5L),
new Double(5.6d), new Float(23.11f),
Boolean.TRUE, new Character('d')
};
staticMeth_0 = getMethodWithName("staticMethodWithoutParams");
staticMeth_6ref = getMethodWithName("staticMethodWithSixObjectParams");
staticMeth_6prim = getMethodWithName("staticMethodWithSixPrimitiveParams");
}
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public static void staticMethodWithoutParams() {
// intentionally left blank
}
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public static void staticMethodWithSixObjectParams(Object o1, Object o2, Object o3, Object o4, Object o5, Object o6) {
// intentionally left blank
}
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public static void staticMethodWithSixPrimitiveParams(int i, long j, double d, float f, boolean z, char c) {
// intentionally left blank
}
/* inner method to get the method to invoke. */
private static Method getMethodWithName(String methodName) {
Method[] methodArray = MethodInvoke.class.getMethods();
for (Method m : methodArray) {
if (m.getName().equals(methodName)) {
return m;
}
}
return null;
}
@Benchmark
public void invokeWithoutParams() throws InvocationTargetException, IllegalAccessException {
staticMeth_0.invoke(null, args_0);
}
@Benchmark
public void invokeWithSixObjectParams() throws Exception {
staticMeth_6ref.invoke(null, args_6ref);
}
@Benchmark
public void invokeWithSixPrimitiveParams() throws Exception {
staticMeth_6prim.invoke(null, args_6prim);
}
}

View File

@ -0,0 +1,226 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.math;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.math.BigDecimal;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class BigDecimals {
/** Make sure TEST_SIZE is used to size the arrays. We need this constant to parametrize the operations count. */
private static final int TEST_SIZE = 100;
/* dummy variables for intermediate results */
public Object[] dummyArr;
public String[] dummyStringArray;
public int dummy;
/* array to hold the created objects. */
private BigDecimal[] bigDecimals;
private String[] stringInputs;
private double[] doubleInputs;
private BigDecimal[] hugeArray, largeArray, smallArray;
@Setup
public void setup() {
Random r = new Random(1123);
dummyArr = new Object[TEST_SIZE];
bigDecimals = new BigDecimal[TEST_SIZE];
stringInputs = new String[TEST_SIZE];
doubleInputs = new double[TEST_SIZE];
for (int i = 0; i < TEST_SIZE; i++) {
double value = (double) (i + 1);
switch (i % 4) {
case 0:
value = -value * 54345.0d;
break;
case 1:
value = value * 5434543453454355e100;
break;
case 2:
value = -value / 5434543453454355e100;
break;
case 3:
break;
}
bigDecimals[i] = new BigDecimal(value);
stringInputs[i] = "" + value;
doubleInputs[i] = value;
}
/*
* Huge numbers larger than MAX_LONG
*/
hugeArray = new BigDecimal[TEST_SIZE];
/*
* Large numbers less than MAX_LONG but larger than MAX_INT
*/
largeArray = new BigDecimal[TEST_SIZE];
/*
* Small number less than MAX_INT
*/
smallArray = new BigDecimal[TEST_SIZE];
dummyStringArray = new String[TEST_SIZE];
for (int i = 0; i < TEST_SIZE; i++) {
int value = Math.abs(r.nextInt());
hugeArray[i] = new BigDecimal("" + ((long) value + (long) Integer.MAX_VALUE)
+ ((long) value + (long) Integer.MAX_VALUE) + ".55");
largeArray[i] = new BigDecimal("" + ((long) value + (long) Integer.MAX_VALUE) + ".55");
smallArray[i] = new BigDecimal("" + ((long) value / 1000) + ".55");
}
}
/** Invokes the (String)-constructor of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testConstructorWithString(Blackhole bh) {
for (String s : stringInputs) {
bh.consume(new BigDecimal(s));
}
}
/** Invokes the (double)-constructor of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testConstructorWithDouble(Blackhole bh) {
for (double s : doubleInputs) {
bh.consume(new BigDecimal(s));
}
}
/** Invokes the toString method of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testToString(Blackhole bh) {
for (BigDecimal s : bigDecimals) {
bh.consume(s.toString());
}
}
/**
* Invokes the setScale method of BigDecimal with various different values.
*/
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testSetScale(Blackhole bh) {
for (BigDecimal s : bigDecimals) {
bh.consume(s.setScale(2, BigDecimal.ROUND_HALF_UP));
}
}
/** Invokes the setScale method of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(50 * TEST_SIZE)
public void testSetScaleVarious(Blackhole bh) {
for (int scale = 0; scale < 50; scale++) {
for (BigDecimal s : bigDecimals) {
bh.consume(s.setScale(scale, BigDecimal.ROUND_HALF_UP));
}
}
}
/** Invokes the add method of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testAdd(Blackhole bh) {
BigDecimal tmp = null;
for (BigDecimal s : bigDecimals) {
if (tmp == null) {
tmp = s;
continue;
}
tmp = tmp.add(s);
}
bh.consume(tmp);
}
/** Invokes the multiply method of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testMultiply(Blackhole bh) {
BigDecimal tmp = null;
for (BigDecimal s : bigDecimals) {
if (tmp == null) {
tmp = s;
continue;
}
tmp = tmp.multiply(s);
}
bh.consume(tmp);
}
/** Invokes the compareTo method of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE - 1)
public void testCompareTo(Blackhole bh) {
BigDecimal c = bigDecimals[0];
for (BigDecimal s : bigDecimals) {
bh.consume(c.compareTo(s));
}
}
/** Test BigDecimal.toString() with huge numbers larger than MAX_LONG */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testHugeToString(Blackhole bh) {
for (BigDecimal s : hugeArray) {
bh.consume(s.toString());
}
}
/** Test BigDecimal.toString() with large numbers less than MAX_LONG but larger than MAX_INT */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testLargeToString(Blackhole bh) {
for (BigDecimal s : largeArray) {
bh.consume(s.toString());
}
}
/** Test BigDecimal.toString() with small numbers less than MAX_INT */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testSmallToString(Blackhole bh) {
for (BigDecimal s : smallArray) {
bh.consume(s.toString());
}
}
}

View File

@ -0,0 +1,140 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.openjdk.bench.java.math;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import java.math.BigInteger;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class BigIntegers {
private BigInteger[] hugeArray, largeArray, smallArray;
public String[] dummyStringArray;
public Object[] dummyArr;
private static final int TESTSIZE = 1000;
@Setup
public void setup() {
Random r = new Random(1123);
hugeArray = new BigInteger[TESTSIZE]; /*
* Huge numbers larger than
* MAX_LONG
*/
largeArray = new BigInteger[TESTSIZE]; /*
* Large numbers less than
* MAX_LONG but larger than
* MAX_INT
*/
smallArray = new BigInteger[TESTSIZE]; /*
* Small number less than
* MAX_INT
*/
dummyStringArray = new String[TESTSIZE];
dummyArr = new Object[TESTSIZE];
for (int i = 0; i < TESTSIZE; i++) {
int value = Math.abs(r.nextInt());
hugeArray[i] = new BigInteger("" + ((long) value + (long) Integer.MAX_VALUE)
+ ((long) value + (long) Integer.MAX_VALUE));
largeArray[i] = new BigInteger("" + ((long) value + (long) Integer.MAX_VALUE));
smallArray[i] = new BigInteger("" + ((long) value / 1000));
}
}
/** Test BigInteger.toString() with huge numbers larger than MAX_LONG */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void testHugeToString(Blackhole bh) {
for (BigInteger s : hugeArray) {
bh.consume(s.toString());
}
}
/** Test BigInteger.toString() with large numbers less than MAX_LONG but larger than MAX_INT */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void testLargeToString(Blackhole bh) {
for (BigInteger s : largeArray) {
bh.consume(s.toString());
}
}
/** Test BigInteger.toString() with small numbers less than MAX_INT */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void testSmallToString(Blackhole bh) {
for (BigInteger s : smallArray) {
bh.consume(s.toString());
}
}
/** Invokes the multiply method of BigInteger with various different values. */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void testMultiply(Blackhole bh) {
BigInteger tmp = null;
for (BigInteger s : hugeArray) {
if (tmp == null) {
tmp = s;
continue;
}
tmp = tmp.multiply(s);
}
bh.consume(tmp);
}
/** Invokes the multiply method of BigInteger with various different values. */
@Benchmark
@OperationsPerInvocation(TESTSIZE)
public void testAdd(Blackhole bh) {
BigInteger tmp = null;
for (BigInteger s : hugeArray) {
if (tmp == null) {
tmp = s;
continue;
}
tmp = tmp.add(s);
}
bh.consume(tmp);
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.net;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
/**
* DatagramSocket micros designed to stress UDP performance.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class DatagramSocketTest {
@Param({"1024", "2048", "4096", "8192", "16384", "32768"})
int size;
private DatagramSocket socket;
private DatagramPacket packet;
@Setup
public void prepare() throws SocketException, UnknownHostException {
socket = new DatagramSocket();
byte[] buf = new byte[size];
packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("localhost"), 9877);
}
@TearDown
public void cleanup() {
socket.close();
}
@Benchmark
public void testSend() throws IOException {
socket.send(packet);
}
}

Some files were not shown because too many files have changed in this diff Show More