【发布时间】:2011-01-27 07:38:31
【问题描述】:
我正在对我的类之间的 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());
}
}
问候
【问题讨论】:
-
“Java 性能框架使编写性能测量代码更容易”?什么这么难?你能解释一下你希望这个框架为你做什么吗?
-
到目前为止,我必须自己编写循环,测量经过的时间。也许有了框架,我不必做那么多的手动编码。
-
@S.Lott:我不是问这个问题的人,但“跳出框框思考”从不伤害任何人。比如说,我可以想象一个框架,它可以通过对两种情况运行 100 次来进行统计性能分析,然后只保留 80% 的值在中值附近,以丢弃异常值。有什么难的呢?你真的想重新发明那个轮子吗?我当然可以写,但如果有一个我可以简单下载的知名工具/API/框架,我会喜欢它...
-
@WizardOfOdds。统计数据,是的:很明显,有人会用一个包来做到这一点。收集统计数据(即通用循环)也许——但它是一行代码。然而,该示例的其余部分不能轻易简化。这就是我要求澄清的原因。我讨厌假设——假设通常是错误的。我没有假设,而是问。
-
有一个名为 ScalaMeter 的 Scala 和 Java 微基准测试框架,您可能想了解一下。网站上的入门指南也提供了很多有用的见解。
标签: java performance multithreading