简体   繁体   English

如何在 Java 中分析阻塞代码——测量执行时间而不是 CPU 时间

[英]how to profile blocking code in java – measure execution time instead of CPU time

I am trying to profile that is often blocking in either database and rest calls.我正在尝试分析经常在数据库和休息调用中阻塞的情况。 The code is not cpu bound.代码不受 CPU 限制。 The following sample junit methods should illustrate the issue:以下示例 junit 方法应说明该问题:

@RepeatedTest(10)
void fast() throws InterruptedException {
    Thread.sleep(100);
}

@RepeatedTest(10)
void slow() throws InterruptedException {
    // imagine a slow database or rest call or any other blocking code
    Thread.sleep(1000);
}

I am using IntelliJ and Java Flight Recorder.我正在使用 IntelliJ 和 Java Flight Recorder。 I expect that method fast is reported as using about 10% of execution time and method slow is using about 90% of execution time.我预计fast方法被报告为使用了大约 10% 的执行时间,而slow方法使用了大约 90% 的执行时间。 But they are not reported at all because they don't eat CPU time.但是它们根本没有报告,因为它们不吃 CPU 时间。

How can I profile the real execution time that includes waiting time in blocking code instead of CPU time only?如何分析实际执行时间,包括阻塞代码中的等待时间,而不仅仅是 CPU 时间?

You need a profiler that understands the semantics of JDBC and HTTP calls.您需要一个了解 JDBC 和 HTTP 调用语义的分析器。 For example, with JProfiler, the profiling agent captures a synthetic Net I/O thread state that is included when the thread status selector is set to "All states".例如,使用 JProfiler,分析代理会捕获合成的 Net I/O 线程状态,当线程状态选择器设置为“所有状态”时会包含该状态。

在此处输入图像描述

Disclaimer: My company develops JProfiler免责声明:我公司开发JProfiler

Async profiler is an excellent, free, and very lightweight tool for JVM profiling. Async profiler 是一个优秀的、免费的、非常轻量级的 JVM 分析工具。 In typical settings, it indeed measures on-CPU time but it has an option to do "Wall-clock" profiling: https://github.com/jvm-profiling-tools/async-profiler#wall-clock-profiling在典型设置中,它确实测量了 CPU 时间,但它可以选择执行“Wall-clock”分析: https ://github.com/jvm-profiling-tools/async-profiler#wall-clock-profiling

You can experiment with that and see if that gives you better results.您可以对此进行试验,看看是否能给您带来更好的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM