Skip to content

Instantly share code, notes, and snippets.

@arwagner
Created October 21, 2012 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arwagner/3927048 to your computer and use it in GitHub Desktop.
Save arwagner/3927048 to your computer and use it in GitHub Desktop.
Bitwise vs. division benchmark
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