Skip to content

Instantly share code, notes, and snippets.

@BrunoBonacci
Created March 23, 2013 00:32
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 BrunoBonacci/5225781 to your computer and use it in GitHub Desktop.
Save BrunoBonacci/5225781 to your computer and use it in GitHub Desktop.
Reminder vs bitwise operation benchmark
/*
* this benchmark compares the speed of
* the reminder operator vs the bitwise
* equivalent.
*/
public class ReminderBenchmark {
final static long d = 8;
final static long mask = d-1;
final static long REPEAT = 1_000_000L;
static long dummy;
public static long reminderWithDivision(long reps) {
long start = System.nanoTime();
for (long i = 0; i < reps; i++) {
dummy = i % d;
}
long stop = System.nanoTime();
return stop-start;
}
public static long reminderWithBitwise(long reps) {
long start = System.nanoTime();
for (long i = 0; i < reps; i++) {
dummy = i & mask;
}
long stop = System.nanoTime();
return stop-start;
}
public static void main(String[] args) throws Exception {
long v1 = 0;
long v2 = 0;
long reps = Long.valueOf(args[0]);
for( int i = 0; i < reps ; i++ ) {
v1 += reminderWithBitwise( REPEAT );
v2 += reminderWithDivision( REPEAT );
}
System.out.println( "average bitwise = " + (v1/reps) );
System.out.println( "average division = " + (v2/reps) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment