Java 性能测量
我正在我的类之间进行一些Java性能比较,并且想知道是否有某种Java性能框架可以使编写性能测量代码更容易?
也就是说,我现在正在做的是试图衡量与使用AtomicInteger作为我的“同步器”相比,它具有像PseudoRandomUsingSynch.nextInt()那样“同步”的方法有什么效果。
因此,我试图测量使用3个线程访问同步方法循环10000次来生成随机整数所需的时间。
我相信有更好的方法来做到这一点。你能启发我吗?:)
public static void main( String [] args ) throws InterruptedException, ExecutionException {
PseudoRandomUsingSynch rand1 = new PseudoRandomUsingSynch((int)System.currentTimeMillis());
int n = 3;
ExecutorService execService = Executors.newFixedThreadPool(n);
long timeBefore = System.currentTimeMillis();
for(int idx=0; idx<100000; ++idx) {
Future<Integer> future = execService.submit(rand1);
Future<Integer> future1 = execService.submit(rand1);
Future<Integer> future2 = execService.submit(rand1);
int random1 = future.get();
int random2 = future1.get();
int random3 = future2.get();
}
long timeAfter = System.currentTimeMillis();
long elapsed = timeAfter - timeBefore;
out.println("elapsed:" + elapsed);
}
类
public class PseudoRandomUsingSynch implements Callable<Integer> {
private int seed;
public PseudoRandomUsingSynch(int s) { seed = s; }
public synchronized int nextInt(int n) {
byte [] s = DonsUtil.intToByteArray(seed);
SecureRandom secureRandom = new SecureRandom(s);
return ( secureRandom.nextInt() % n );
}
@Override
public Integer call() throws Exception {
return nextInt((int)System.currentTimeMillis());
}
}
问候