本文介绍了测量代码段的Java执行时间,内存使用和CPU负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于特定的Java代码段,我想测量:


  • 执行时间(很可能线程执行时间

  • 内存使用

  • CPU负载(特别是可归因于代码段)

  • Execution time (most likely thread execution time)
  • Memory usage
  • CPU load (specifically attributable to the code segment)

我是相对Java新手而且我是不熟悉如何实现这一目标。我已经被提到,但是我不确定如何使用它,和JMX看起来有点沉重我想要做的事情。

I'm a relative Java novice and am not familiar with how this might be achieved. I've been referred to JMX, however I'm not sure how that might be used, and JMX looks a bit 'heavy' for what I'm looking to do.

理想情况下我想要一些测量类可以告诉我想测量什么,可选择在代码段之前调用 start()方法,然后调用 stop()方法。相关指标将记录到我指定的文件中。

Ideally I'd like some measurement class that can be told what I would like to measure, with the option of calling a start() method prior to a code segment and a stop() method after. Relevant metrics would be logged to a file I specify.

例如:

import com.example.metricLogger;

metricLogger logger = new metricLogger();

logger.setLogPath(pathToLogFile);
logger.monitor(executionTime);
logger.monitor(memoryUsage);
logger.monitor(cpuLoad);

logger.start();

/* Code to be measured */

logger.stop();

在Java中是否有任何标准/通用/传统方式实现此目的?

此类测量用于一次性性能比较,因此我不会寻找任何正在进行中的长期监测过程。

Such measurements are for one-off performance comparisons, and so I'm not looking for any in-production long-term monitoring processes.

我很高兴被引用到教程或外部示例,并且不希望在这里得到完整答案。也就是说,如果能够实现上述任何简单的事情,那么真实的例子就会很好。

I'm more than happy to be referred to tutorials or external examples and don't expect a full answer here. That said, if anything as simple as the above can be achieved a realistic example would go down really well.

推荐答案

分析可能是一个更简单的选项,因为您不需要生产中的统计数据。分析也不需要修改代码。 VisualVM(随JDK 1.6.06+发布)是一个简单的工具。如果你想要更深入的东西,我会选择Eclipse TPTP,Netbeans profiler或JProfiler(付费)。

Profiling may be an easier option since you don't require in-production stats. Profiling also doesn't require code modification. VisualVM (which ships w/ the JDK 1.6.06+) is a simple tool. If you want something more in-depth I'd go with Eclipse TPTP, Netbeans profiler, or JProfiler(pay).

如果你想自己写,请考虑以下:

If you want to write you own, consider the following:

执行时间之类的简单测量可以通过计时您感兴趣的部分来完成:

Simple measurments like execution time can be done by "clocking" the section you're interested in:

long start = System.nanoTime(); // requires java 1.5
// Segment to monitor
double elapsedTimeInSec = (System.nanoTime() - start) * 1.0e-9;

您可以使用类似的技术通过Runtime.getRuntime()监视内存。* memory()方法。请记住,在垃圾收集环境中跟踪内存使用比简单减法更棘手。

You can use a similar technique to monitor memory via Runtime.getRuntime().*memory() methods. Keep in mind that tracking memory usage in a garbage collected environment is trickier than simple subtraction.

在Java中很难衡量CPU负载,我通常会坚持执行时间和优化较长/重复的部分

CPU load is hard to measure in Java, I typically stick with execution time and optimize the longer / repetitive sections

这篇关于测量代码段的Java执行时间,内存使用和CPU负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 00:54