Created
October 23, 2019 06:13
-
-
Save timedcy/3c650774d1aef5a08fe858f1572dcd17 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ddzj.learnjava; | |
import lombok.extern.slf4j.Slf4j; | |
import org.openjdk.jmh.annotations.*; | |
import org.openjdk.jmh.runner.Runner; | |
import org.openjdk.jmh.runner.RunnerException; | |
import org.openjdk.jmh.runner.options.Options; | |
import org.openjdk.jmh.runner.options.OptionsBuilder; | |
import java.util.Random; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* ClassName: CPUBranchPredictionTest <br/> | |
* Function: <br/> | |
* Date: 2019-10-23 9:15<br/> | |
* | |
* @author timedcy | |
* @version 0.1 | |
*/ | |
@Slf4j | |
@BenchmarkMode(Mode.AverageTime) | |
@OutputTimeUnit(TimeUnit.MILLISECONDS) | |
@State(Scope.Thread) | |
public class CPUBranchPredictionTest { | |
int[] data; | |
@Setup | |
public void setUp() { | |
int loopNum = 2_000_000; | |
data = new int[loopNum]; | |
Random random = new Random(42); | |
for (int i = 0; i < loopNum; i++) { | |
data[i] = random.nextInt(); | |
} | |
} | |
@Benchmark | |
public long testIfBranch() { | |
long sum = 0L; | |
int loopNum = data.length; | |
for (int i = 0; i < loopNum; i++) { | |
if ((data[i] & 1) == 1) { | |
sum += i; | |
} | |
} | |
return sum; | |
} | |
@Benchmark | |
public long testNoBranch() { | |
long sum = 0L; | |
int loopNum = data.length; | |
for (int i = 0; i < loopNum; i++) { | |
sum += (data[i] & 1) * i; | |
} | |
return sum; | |
} | |
@Benchmark | |
public long testIsDebugedNoBranch() { | |
long sum = 0L; | |
int loopNum = data.length; | |
for (int i = 0; i < loopNum; i++) { | |
if (log.isDebugEnabled()) { | |
sum += (data[i] & 1) * i; | |
} | |
} | |
return sum; | |
} | |
public static void main(String[] args) throws RunnerException { | |
log.info("log.isDebugEnabled(): {}", log.isDebugEnabled()); | |
Options opt = new OptionsBuilder() | |
.include(CPUBranchPredictionTest.class.getSimpleName()) | |
.forks(1) | |
.warmupIterations(1) | |
.measurementIterations(5) | |
.build(); | |
new Runner(opt).run(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment