简体   繁体   English

什么是获得经过时间并重置它的正确方法

[英]Whats is the right way to get elapsed time and reset it

In my android program I am using two Calendar instances to get the elapsed time in my program, first I set a level starting time as follows: 在我的android程序中,我使用两个Calendar实例来获取程序中的已用时间,首先我设置一个级别开始时间如下:

level_Start_TimeCal = Calendar.getInstance();   

and in my thread I am calculating elapsed time as follows: 在我的线程中,我按如下方式计算经过时间:

level_current_TimeCal = Calendar.getInstance();
gameTime = level_current_TimeCal.getTimeInMillis()- level_Start_TimeCal.getTimeInMillis();                      
dsecs = (gameTime / 1000)%60;
dminutes = (gameTime / (60 * 1000))%60;
dhours = (gameTime / (60 * 60 * 1000))%60;

Recently I came to read the following: 最近我来看了以下内容:

Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time Calendar的getInstance方法返回一个Calendar对象,其日历字段已使用当前日期和时间进行初始化

I want to know if I am in right path? 我想知道我是否走在正确的道路上?
Am I creating an object each time the thread running? 每次线程运行时我都会创建一个对象吗?
If yes is there any alternative to avoid creating unwanted objects and calculating elapsed time? 如果是,是否有任何替代方法可以避免创建不需要的对象并计算经过的时间? Final question: at some point I want to reset the time in my restart method I reset it by just calling getInstance in my reset method as follows: 最后一个问题:在某些时候我想在重启方法中重置时间我只需在我的reset方法中调用getInstance重置它,如下所示:

public void restart() {
 level_Start_TimeCal = Calendar.getInstance();
}

Is this the correct way to reset the Calendar? 这是重置日历的正确方法吗?

The best way to calculate elapsed time is to use System.nanotime() . 计算经过时间的最佳方法是使用System.nanotime()

long start = System.nanoTime();
//do something
long end = System.nanoTime();

//to get the elapsed time, you can use the TimeUnit utility methods:
long elapsedInNanos = end - start;
long elapsedInSeconds = TimeUnit.SECONDS.convert(elapsedInNanos, TimeUnit.NANOSECONDS);

Note that it is not a useful method to access absolute time. 请注意,访问绝对时间不是一种有用的方法。

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

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