OnJava8-Examples/tasks/SimpleMicroBenchmark.java

53 lines
1.4 KiB
Java
Raw Normal View History

2016-01-25 18:05:55 -08:00
// tasks/SimpleMicroBenchmark.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// The dangers of microbenchmarking
2015-06-15 17:47:35 -07:00
import java.util.concurrent.locks.*;
abstract class Incrementable {
protected long counter = 0;
public abstract void increment();
}
class SynchronizingTest extends Incrementable {
@Override
public synchronized void increment() { ++counter; }
}
class LockingTest extends Incrementable {
private Lock lock = new ReentrantLock();
@Override
public void increment() {
lock.lock();
try {
++counter;
} finally {
lock.unlock();
}
}
}
public class SimpleMicroBenchmark {
static long test(Incrementable incr) {
long start = System.nanoTime();
for(long i = 0; i < 10000000L; i++)
incr.increment();
return System.nanoTime() - start;
}
public static void main(String[] args) {
long synchTime = test(new SynchronizingTest());
long lockTime = test(new LockingTest());
2016-01-25 18:05:55 -08:00
System.out.printf(
"synchronized: %1$10d\n", synchTime);
2015-06-15 17:47:35 -07:00
System.out.printf("Lock: %1$10d\n", lockTime);
System.out.printf("Lock/synchronized = %1$.3f",
(double)lockTime/(double)synchTime);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
synchronized: 243572959
Lock: 365176719
Lock/synchronized = 1.499
2015-09-07 11:44:36 -06:00
*/