[英]How to Measure execution time for a multi threaded task in java
我有一个方法可以让我们说对 API 的 100k http 调用,因此我同时进行 http 调用以避免 http 瓶颈。 但我也想在不阻塞任何线程的情况下对整个方法进行计时。
ExecutorService service = Executors.newFixedThreadPool(500);
for (int i = 0; i < 100_000; i++) {
int finalI = i;
Runnable runnable = () -> {
// My http call goes here....
};
service.submit(runnable);
}
如果您想大致了解整个操作集所花费的时间,请使用shutdown
然后awaitTermination
来等待 executor 服务完成所有提交的任务。 这是一个简单的例子:
long start= System.nanoTime();
ExecutorService exec = Executors.newFixedThreadPool(100);
try {
for (int i = 0; i < 100_000; i++) {
final int x = i;
Runnable runnable = () -> System.out.println(x);
exec.submit(runnable);
}
} finally {
exec.shutdown();
exec.awaitTermination(365, TimeUnit.DAYS);
}
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed millisec "+TimeUnit.NANOSECONDS.toMillis(elapsed));
将System.out.println
或其他日志记录放在任务中并不是一个好主意,因为您只是在为控制台 I/O 计时,而不是估计您的处理速度。
如评论中所述,对同一组服务器/资源/磁盘使用多线程访问可能会使整体经过的时间变长或在其他地方引起问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.