Current time in millis second and nano second
In this chapter you will learn:
- How to get current time in nano seconds
- How to get current time in millis seconds
- How to time the performance of a for loop
Current nano time
static long nanoTime()
from System
class
Returns the current value of the most precise available system timer, in nanoseconds.
public class Main {
//from j a v a 2 s . co m
public static void main(String args[]) {
System.out.println(System.nanoTime());
}
}
The output:
get current time in millis seconds
static long currentTimeMillis()
from System
class
Returns the current time in milliseconds.
public class Main {
// j a v a 2s .co m
public static void main(String args[]) {
System.out.println(System.currentTimeMillis());
}
}
The output:
Time a for loop
The following code uses the System.currentTimeMillis()
to check the performance of a for loop.
public class Main {
public static void main(String args[]) {
long start, end;
//from j a v a2s . co m
System.out.println("Timing a for loop from 0 to 1,000,000");
start = System.currentTimeMillis(); // get starting time
for (int i = 0; i < 9999999; i++)
;
end = System.currentTimeMillis(); // get ending time
System.out.println("Elapsed time: " + (end - start));
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Utility Classes