This question already has answers here:
How to measure elapsed time

(5个答案)


3年前关闭。




我目前正在研究测验游戏,我希望能够在游戏开始时启动计时器,然后在游戏结束时结束计时器。然后,我想打印出玩家完成游戏所需的时间。有没有简单的方法可以做到这一点?

编辑:谢谢xenteros!我要做的就是从“长差= stopTime-startTime;”中删除“ long”。 ,在该行代码之前创建一个变量,例如“长差异;”,然后初始化“ startTime”变量。

最佳答案

如果您的用户行为是单一方法,则代码应为:

long startTime = System.currentTimeMillis();
//the method
long stopTime = System.currentTimeMillis();
long difference = stopTime - startTime;
System.out.println("The task took: " + difference + " milliseconds");
System.out.println("The task took: " + difference/1000 + " seconds");


上面是用Java做到这一点的正确方法。

为了您的舒适:

public static void main() {
    long startTime, stopTime;
    //some code
    startTime = System.currentTimeMillis(); //right before user's move
    //user's move
    stopTime = System.currentTimeMillis();
    long difference = stopTime - startTime;
    System.out.println("The task took: " + difference + " milliseconds");
    System.out.println("The task took: " + difference/1000 + " seconds");

}

10-05 23:14