Java System currentTimeMillis() example

In this guide, you will learn about the System currentTimeMillis() method in Java programming and how to use it with an example.

1. System currentTimeMillis() Method Overview

Definition:

The currentTimeMillis() method of the System class returns the current time in the format of milliseconds. Milliseconds will be returned as a unit of time.

Syntax:

public static long currentTimeMillis()

Parameters:

None.

Key Points:

- It returns the difference between the current time and the Unix epoch in milliseconds.

- Useful for benchmarking, measuring elapsed time, or generating unique timestamps.

- The method provides millisecond precision, but the actual precision might be affected by the operating system, JVM, and system hardware.

- It's monotonic, which means the returned value will always be non-decreasing as long as the JVM process is alive.

2. System currentTimeMillis() Method Example 1

public class SimpleTimeExample {

    public static void main(String[] args) {

        // Get the current time in milliseconds
        long currentTimeMillis = System.currentTimeMillis();

        // Display the current time in milliseconds
        System.out.println("Current Time in Milliseconds = " + currentTimeMillis);
    }
}

Output:

Current Time in Milliseconds = 1695707898392

Explanation:

When you run this program, it will print the current time in milliseconds to the console. Keep in mind that this value will change every time you run the program since it represents the current time.

3. System currentTimeMillis() Method Example 2

public class TimeBenchmarkingExample {
    public static void main(String[] args) {
        // capture the start time
        long startTime = System.currentTimeMillis();

        // simulate some work by pausing the program for 2 seconds
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // capture the end time
        long endTime = System.currentTimeMillis();

        // calculate and print the elapsed time
        System.out.println("Elapsed time: " + (endTime - startTime) + " milliseconds");
    }
}

Output:

Elapsed time: 2000 milliseconds

Explanation:

In this example, we are using currentTimeMillis() to benchmark how long it takes to execute a piece of code. We capture the time before and after the simulated work (in this case, a sleep of 2 seconds) and then compute the difference. The output should be roughly 2000 milliseconds (or 2 seconds), though it might vary slightly due to overhead and the precision of the system timer.

Comments