Created
October 21, 2012 14:01
-
-
Save arwagner/3927048 to your computer and use it in GitHub Desktop.
Bitwise vs. division benchmark
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
public class Main { | |
static final int CALCULATIONS_PER_TRIAL = 10000000; | |
static final int TRIALS_PER_RUN = 100; | |
public static void main(String[] args) throws InterruptedException{ | |
int bitwiseWins = 0; | |
for (int trial = 0; trial < TRIALS_PER_RUN; trial++){ | |
long modulusStart = System.nanoTime(); | |
for (int calculation = 0; calculation < TRIALS_PER_RUN; calculation++){ | |
int result = calculation % 64; | |
Thread.sleep(1); | |
} | |
long modulusTime = System.nanoTime() - modulusStart; | |
long bitwiseStart = System.nanoTime(); | |
for (int calculation = 0; calculation < TRIALS_PER_RUN; calculation++){ | |
int result = calculation & 63; | |
Thread.sleep(1); | |
} | |
long bitwiseTime = System.nanoTime() - bitwiseStart; | |
System.out.println("Trial #" + trial + ": bitwise=" + bitwiseTime + ", modulus=" + modulusTime); | |
if (bitwiseTime < modulusTime){ | |
bitwiseWins++; | |
} | |
} | |
System.out.println("bitwise operations performed better " + (bitwiseWins*1.0/TRIALS_PER_RUN)*100 + " percent of the time"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment