java代码执行时间分析,测量代码段的Java执行时间,内存使用和CPU负载

For a particular segment of Java code, I'd like to measure:

Execution time (most likely thread execution time)

Memory usage

CPU load (specifically attributable to the code segment)

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.

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.

For example:

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();

Is there any standard/common/conventional way of achieving this in 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.

解决方案

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;

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值