Measuring Thread Execution Time in Java

Wall-Clock Time Tracking with System.nanoTime()

To evaluate the total elapsed duration of a thread's lifecycle from start to finish, recording timestamps before and after the execution logic is the most straightforward approach. The System.nanoTime() method offers a high-resolution time source that is perfectly suited for measuring elapsed time, unaffected by system clock adjustments.


long initNanos = System.nanoTime();
// Execute target thread logic here
long completionNanos = System.nanoTime();
long elapsedMillis = (completionNanos - initNanos) / 1_000_000;

CPU Time Measurement with ThreadMXBean

Wall-clock time includes periods where a thread is waiting, sleeping, or blocked, which does not reflect actual CPU consumption. To measure the precise CPU time utilized by a thread, the ThreadMXBean management interface can be utilized. It allows you to query the user and system CPU time for a specific thread ID.


ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
long targetTid = Thread.currentThread().getId();
long consumedCpuNanos = mxBean.getThreadCpuTime(targetTid);
long consumedCpuMillis = consumedCpuNanos / 1_000_000;

Implementation Example: Wall-Clock vs. CPU Time

The following example illustrates how to capture both wall-clock duration and actual CPU processing time. The task is designed with a sleep period to clearly distinguish between elapsed time and CPU consumption.


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

public class ThreadTimingDemo {

    public static void main(String[] args) throws InterruptedException {
        long appStartNanos = System.nanoTime();

        Thread worker = new Thread(() -> {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean();
            long cpuStartNanos = bean.getCurrentThreadCpuTime();

            try {
                // Simulate I/O wait (does not consume CPU)
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            // Simulate CPU-intensive computation
            int sum = 0;
            for (int i = 0; i < 500_000; i++) {
                sum += i;
            }

            long cpuEndNanos = bean.getCurrentThreadCpuTime();
            System.out.println("Task CPU Time: " + (cpuEndNanos - cpuStartNanos) / 1_000_000 + " ms");
        }, "Worker-Thread");

        worker.start();
        worker.join();

        long appEndNanos = System.nanoTime();
        System.out.println("Total Wall-Clock Time: " + (appEndNanos - appStartNanos) / 1_000_000 + " ms");
    }
}

Tags: java ThreadMXBean System.nanoTime multithreading

Posted on Tue, 16 Jun 2026 17:04:51 +0000 by Rupuz