简体   繁体   中英

How to print time elapsed (seconds) java

in my run method of a game loop I tried to print the time the program has been running in java. I simply tried System.out.println(System.nanoTime() / 1000000); because that's how many milliseconds are in a second.(if you didn't know) It prints the seconds near the end but I wanted exact seconds for testing purposes. I searched online and someone suggested using the same formula I thought of. Can anyone give an exact one?

Store previous time in a private member.

private long previousTime;

Initialize it in the constructor.

previousTime = System.currentTimeMillis();

Compare it with current time in run method (each iteration of game loop)

long currentTime = System.currentTimeMillis();
double elapsedTime = (currentTime - previousTime) / 1000.0;
System.out.println("Time in seconds : " + elapsedTime);
previousTime = currentTime;

In addition to the other answers provided, you could use a standard library StopWatch , like the one provided by Google's Guava API:

Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
calculate();
stopwatch.stop(); // optional

long Seconds= stopwatch.elapsedMillis() / 1000000; // equals 1 second

You can use System.currentTimeMillis to get the current time in milliseconds.

If you pick this value at the start of your application and at the end, the subtraction of both values will give you the time your application was running.

final long start = System.currentTimeMillis();
// your code here...
final long end = System.currentTimeMillis();
System.out.println("The program was running: " + (end-start) + "ms.");

If you want it in seconds, just divide it with 1000 like you mentioned.

System.out.println("The program was running: " + ((double)(end-start)/1000.0d) + "ms.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM