Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure Java thread execution time?

I want to measure thread execution time in Java. Now I'm monitoring thread start and end times, but I think it's not so accurate because thread could be suspended during it execution.

like image 345
giolekva Avatar asked May 06 '10 11:05

giolekva


People also ask

How is thread execution time calculated?

How do you calculate: Log time intervals when the thread starts and at swap-in and swap-out. Aggregate all of them and you'll have the execution time of your thread.

How do you calculate execution time in Java?

The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds.

How do you calculate execution time?

The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.

How do I monitor JVM threads?

The simplest way to see the number of threads in Java is to use a graphical tool like Java VisualVM. Apart from the application threads, Java VisualVM also lists the GC or any other threads used by the application like JMX threads. Monitoring the number of threads is the most basic feature in Java VisualVM.


2 Answers

Java MXBeans can provide per-thread CPU time:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

long nanos = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId());
like image 171
David Koski Avatar answered Oct 28 '22 05:10

David Koski


This is nontrivial. Your best bet is to use a profiler which can accumulate the actual CPU cycles used.

like image 25
Aaron Digulla Avatar answered Oct 28 '22 07:10

Aaron Digulla