Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure the a time-span in seconds using System.currentTimeMillis()?

How to convert System.currentTimeMillis(); to seconds?

long start6=System.currentTimeMillis();
System.out.println(counter.countPrimes(100000000)+" for "+start6);

The console shows me 5761455 for 1307816001290. I can't read how many seconds that is.

Any help?

like image 906
J13t0u Avatar asked Jun 11 '11 18:06

J13t0u


People also ask

What does system currentTimeMillis () do?

currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

How do you obtain the current minute using the system currentTimeMillis () method?

System. currentTimeMillis() returns the current time in milliseconds. The method returns time difference in milliseconds between the current time and midnight, January 1, 1970 (UTC or epoch time).

How long is system currentTimeMillis?

System. currentTimeMillis() returns a Java long . It will always be exactly 64 bits long and will typically have a number of leading zeroes.

How accurate is system currentTimeMillis?

This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Depending on the system, it can take more than 100 cpu cycles to execute.


3 Answers

TimeUnit

Use the TimeUnit enum built into Java 5 and later.

long timeMillis = System.currentTimeMillis(); long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis); 
like image 57
JH. Avatar answered Sep 19 '22 08:09

JH.


long start = System.currentTimeMillis();
counter.countPrimes(1000000);
long end = System.currentTimeMillis();

System.out.println("Took : " + ((end - start) / 1000));

UPDATE

An even more accurate solution would be:

final long start = System.nanoTime();
counter.countPrimes(1000000);
final long end = System.nanoTime();

System.out.println("Took: " + ((end - start) / 1000000) + "ms");
System.out.println("Took: " + (end - start)/ 1000000000 + " seconds");
like image 23
Nico Huysamen Avatar answered Sep 20 '22 08:09

Nico Huysamen


like so:

(int)(milliseconds / 1000)
like image 40
Stas Jaro Avatar answered Sep 18 '22 08:09

Stas Jaro