Backend Development 10 min read

Various Methods for Measuring Code Execution Time in Java

This article introduces four practical approaches for measuring code execution time in Java—including simple time‑difference calculation, StopWatch‑style utilities, functional interfaces with Supplier/IntConsumer, and AutoCloseable‑based tracing—providing code examples, usage patterns, and enhancements such as chainable start methods.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Various Methods for Measuring Code Execution Time in Java

Measuring code execution time is a common requirement in Java development, especially when identifying performance bottlenecks. Traditional time‑difference statistics involve recording a start timestamp and an end timestamp, then computing the delta, but this approach can clutter business logic.

Conventional Methods

Time Difference Statistics

The simplest method records the start time, performs the business logic, then records the end time and calculates the difference.

public class TimeDiffTest {
    public static void main(String[] args) throws InterruptedException {
        final long startMs = TimeUtils.nowMs();
        TimeUnit.SECONDS.sleep(5); // simulate business code
        System.out.println("timeCost: " + TimeUtils.diffMs(startMs));
    }
}

public class TimeUtils {
    /** @return current milliseconds */
    public static long nowMs() {
        return System.currentTimeMillis();
    }
    /** @param startMillis start time */
    public static long diffMs(long startMillis) {
        return diffMs(startMillis, nowMs());
    }
}

This method is easy to understand but intrusive to the code.

StopWatch

Many frameworks provide a StopWatch utility for timing code blocks.

public class TraceWatchTest {
    public static void main(String[] args) throws InterruptedException {
        TraceWatch traceWatch = new TraceWatch();
        traceWatch.start("function1");
        TimeUnit.SECONDS.sleep(1); // simulate business code
        traceWatch.stop();
        traceWatch.start("function2");
        TimeUnit.SECONDS.sleep(1);
        traceWatch.stop();
        traceWatch.record("function1", 1);
        System.out.println(JSON.toJSONString(traceWatch.getTaskMap()));
    }
}

public class TraceWatch {
    private long startMs;
    private String currentTaskName;
    private final Map
> taskMap = new HashMap<>();
    public void start(String taskName) throws IllegalStateException { /* ... */ }
    public void stop() throws IllegalStateException { /* ... */ }
    public void record(String taskName, Object data) { /* ... */ }
    @Getter @AllArgsConstructor
    public static final class TaskInfo {
        private final String taskName;
        private final Object data;
    }
}

Advanced Methods

Function (java.util.function)

Using Supplier and IntConsumer allows timing of arbitrary code blocks without manual start/stop calls.

public class TraceHolderTest {
    public static void main(String[] args) throws InterruptedException {
        TraceWatch traceWatch = new TraceWatch();
        TraceHolder.run(traceWatch, "function1", i -> {
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        });
        String result = TraceHolder.run(traceWatch, "function2", () -> {
            try { TimeUnit.SECONDS.sleep(1); return "YES"; }
            catch (InterruptedException e) { e.printStackTrace(); return "NO"; }
        });
        System.out.println(JSON.toJSONString(traceWatch.getTaskMap()));
    }
}

public class TraceHolder {
    public static
T run(TraceWatch traceWatch, String taskName, Supplier
supplier) {
        try { traceWatch.start(taskName); return supplier.get(); }
        finally { traceWatch.stop(); }
    }
    public static void run(TraceWatch traceWatch, String taskName, IntConsumer function) {
        try { traceWatch.start(taskName); function.accept(0); }
        finally { traceWatch.stop(); }
    }
}

AutoCloseable

Implementing AutoCloseable on TraceWatch enables try‑with‑resources syntax for even cleaner timing.

public class AutoCloseableTest {
    public static void main(String[] args) {
        TraceWatch traceWatch = new TraceWatch();
        try (TraceWatch ignored = traceWatch.start("function1")) {
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        try (TraceWatch ignored = traceWatch.start("function2")) {
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        System.out.println(JSON.toJSONString(traceWatch.getTaskMap()));
    }
}

// Modification of TraceWatch.start to support chaining
public TraceWatch start(String taskName) throws IllegalStateException {
    if (this.currentTaskName != null) {
        throw new IllegalStateException("Can't start TraceWatch: it's already running");
    }
    this.currentTaskName = taskName;
    this.startMs = TimeUtils.nowMs();
    return this;
}

@Override
public void close() {
    this.stop();
}

Summary

The article presents four ways to measure code execution time in Java:

Simple time‑difference calculation

StopWatch‑style utilities

Functional interfaces (Supplier/IntConsumer)

AutoCloseable with try‑with‑resources

These approaches balance simplicity, readability, and elegance, allowing developers to choose the most suitable method for their projects.

JavaPerformanceAutoCloseableTimingStopWatch
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.