开发者

Profile CPU usage in Java on a Mac

I'm looking for a way to measure the cpu usage for different methods in my j开发者_运维问答ava code. I understand that this can be achieved using JNI and C, but I wouldn't know where to start...

The purpose of this is to compare different algorithms, and provide qualitative results.


Probably the most common way is to use sampling. The JVM provides facilities to ask it the current stack trace of all threads (or ones you're interested in), along with how much CPU they've consumed. So you periodically do this. On each call, if a thread is inside the method you're interested in, then assume that it's spent half of the reported CPU time since the last poll inside that method.

If this method sounds appropriate, a little while back I wrote some material on the Java 5 profiling facilities that might help you.

Java 5 also provides an Instrumentation framework, by which you can doctor classes as they're being loaded in to include calls on the entry and exit to your given method, so you can measure CPU usage just inside that method. However, this is a little more complex to program because you need to doctor the actual class binaries as they're being loaded.


I don't think you can really identify CPU usage down to the method level with the current range of profilers. For most methods it's pretty obvious (if the method is compute-bound and single-threaded then it'll use 100% of CPU subject to allocation by the OS).

You may want to identify hot-spots though (methods consuming more CPU than you'd anticipate - or possibly less?) and I'd recommend looking at YourKit for an easy-to-configure profiler.

Failing that, take a look at the JVM Profiling Interface (JVMPI), which may give you some further pointers.


Sun VisualVM is integrated in recent JDK's and its profiling capabilities are explained here. Note that it seems to require a pretty up to date version of OSX if I understand this correctly.
Netbeans has basically the same profiling machinery on board, I don't know if that's of any help.


If you want to use one of already available profiling tools, then you can try Shark


Have a look at the OperatingSystemMXBean perhaps you could look at something before and after your method

long startProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
long endProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();

Java6 only


I I'm not sure if this is what you want but I've used jrat for profiling in the past with decent results.


Check JaMon. Is very easy to use.


Call your methods in separate threads and measure the delta of time before and after execution of given procedure.

To measure the time of a process call:

    ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
    long threadTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜