TimeToCodeTheRoad
TimeToCodeTheRoad

Reputation: 7312

Recording Program's CPU Time

I want to record the time taken by my Java program. Most forums suggest something like:

int starttime=System.nanoTime();  
//program code  
int endTime=System.nanoTime();  
int timetaken=starttime-endTime;  

The problem with this approach is that if there are multiple programs running, then the difference between endTime and starttime is not the time taken by my program. It is also the time taken during scheduling of different programs in the CPU etc. However, I am only interested to record the time taken by my program. How do I get this time?

Upvotes: 0

Views: 544

Answers (1)

radai
radai

Reputation: 24192

you can find the answer in this article. to quote from the article:

Call ManagementFactory . getThreadMXBean() to get a ThreadMXBean that describes current JVM threads. The bean's getCurrentThreadCpuTime() method returns the CPU time for the current thread. The getCurrentThreadUserTime() method returns the thread's user time. Both of these report times in nanoseconds

if your application is multi-threaded you'd need to record the cpu time per application thread and sum them up to get the total cpu time taken up by your application across all of its threads.

having said that - if youre really serious about profiling your cpu consumption you should probably be using a profiler. you can start with a free open source one like visualvm (also comes bundled with the jdk) which will (among many other things) answer this exact question very easily.

Upvotes: 2

Related Questions