Don*_* Ch 13 java performance multithreading
我正在我的类之间进行一些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);
}
Run Code Online (Sandbox Code Playgroud)
班级
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());
}
}
Run Code Online (Sandbox Code Playgroud)
问候
更多微基准测试建议 - 微基准测试很少告诉您真正需要知道的内容......实际应用程序的运行速度有多快.
在您的情况下,我想您正试图弄清楚您的应用程序使用Atomic对象的性能是否优于使用synchronized ...或反之亦然.真正的答案是,它很可能取决于微基准无法衡量的因素.诸如争用的可能性,持有锁的时间,线程和处理器的数量,以及使原子更新成为可行解决方案所需的额外算法工作量.
编辑 - 回答这个问题.
那么有没有办法可以衡量所有这些争用概率,锁定持续时间等?
理论上是的.一旦实现了整个应用程序,就可以对其进行检测以测量这些内容.但这也没有给你答案,因为没有预测模型你可以插入这些数字来给出答案.此外,您已经实施了该应用程序.
但我的观点并不是衡量这些因素可以让你预测表现.(它不!)相反,它是一个微型基准不会让你预测的性能无论是.
实际上,最好的方法是根据您的直觉实现应用程序,然后使用性能分析作为确定实际性能问题所在的基础.
这些人设计了一个很好的 JVM 测量方法,这样你就不会用虚假的数字来欺骗自己,然后将其发布为 Python 脚本,这样你就可以重复使用他们的聪明才智 -
OpenJDK家伙开发了一种称为JMH的基准测试工具:
http://openjdk.java.net/projects/code-tools/jmh/
这提供了一个非常容易设置的框架,并且有几个示例说明了如何使用它。
没有什么可以阻止您编写错误的基准测试,但是它们在消除非显而易见的错误(例如线程之间的错误共享,防止无效代码消除等)方面做得很好。