简体   繁体   English

如何打印经过的时间(秒)java

[英]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. 在我的游戏循环方法中,我试图打印程序在java中运行的时间。 I simply tried System.out.println(System.nanoTime() / 1000000); 我只是尝试了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) 将它与run方法中的当前时间进行比较(游戏循环的每次迭代)

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 ,就像Google的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. 您可以使用System.currentTimeMillis以毫秒为单位获取当前时间。

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. 如果你想在几秒钟内完成,只需将它除以你提到的1000。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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