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.
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.
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.
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.
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.
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());
This is nontrivial. Your best bet is to use a profiler which can accumulate the actual CPU cycles used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With