Reputation: 3
I want to give the program time in java. How can I get the time in seconds? This is my program:
public static void main(String[] args) {
long start = System.nanoTime();
System.out.print(start);
}
For example when i run the program show 7955739220574 nano time. that mean's 7955 second. Is this time is really for this program!!!!!? Thank you.
Upvotes: 0
Views: 80
Reputation: 2755
Please note that System.nanoTime()
returns the time in nanoseconds which passed since an arbitrary point in time, not necessarily the beginning of your program. System.currentTimeMillis()
will give you the absolute time in milliseconds since the Unix epoch (Jan 1, 1970).
If you want to measure the duration of something you can do:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
... as showed in the docs i linked. If you want it in seconds you should divide estimatedTime
it by 1 billion.
Upvotes: 1
Reputation: 2124
You could use TimeUnit:
TimeUnit.SECONDS.convert(time, TimeUnit.NANOSECONDS);
Upvotes: 1
Reputation: 5433
1 nanosecond
is 10^-9 * 1 seconds
.
so to get seconds using nano seconds, you need to divide the value of Start
by 10^-9
Upvotes: 0