我想要这样的东西:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
同样重要的是,例如,如果startTime是23:00,endTime是1:00,则持续时间为2:00。
为了在Java中实现这一点,应该使用哪些类型?
我想要这样的东西:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
同样重要的是,例如,如果startTime是23:00,endTime是1:00,则持续时间为2:00。
为了在Java中实现这一点,应该使用哪些类型?
当前回答
不幸的是,目前发布的十个答案中没有一个是完全正确的。
如果您正在测量经过的时间,并且希望它是正确的,那么必须使用System.nanoTime()。您不能使用System.currentTimeMillis(),除非您不介意结果是错误的。
The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.
由于nanoTime的目的是测量经过的时间,因此它不受任何这些小修正的影响。它是你想要使用的。当前使用currentTimeMillis进行的任何计时都将关闭——甚至可能为负值。
您可能会说,“这听起来似乎并没有那么重要”,对此我说,也许不是,但总的来说,正确的代码不就是比错误的代码好吗?此外,nanoTime打字时间更短。
之前发布的关于nanoTime通常只有微秒精度的免责声明是有效的。此外,它可能需要超过一微秒的时间来调用,这取决于环境(另一个也是如此),所以不要期望对非常非常小的间隔进行正确的计时。
其他回答
我建立了一个格式化函数,基于我偷来的东西。我需要一种方法来“分析”日志消息中的内容,所以我需要一个固定长度的持续时间消息。
public static String GetElapsed(long aInitialTime, long aEndTime, boolean aIncludeMillis)
{
StringBuffer elapsed = new StringBuffer();
Map<String, Long> units = new HashMap<String, Long>();
long milliseconds = aEndTime - aInitialTime;
long seconds = milliseconds / 1000;
long minutes = milliseconds / (60 * 1000);
long hours = milliseconds / (60 * 60 * 1000);
long days = milliseconds / (24 * 60 * 60 * 1000);
units.put("milliseconds", milliseconds);
units.put("seconds", seconds);
units.put("minutes", minutes);
units.put("hours", hours);
units.put("days", days);
if (days > 0)
{
long leftoverHours = hours % 24;
units.put("hours", leftoverHours);
}
if (hours > 0)
{
long leftoeverMinutes = minutes % 60;
units.put("minutes", leftoeverMinutes);
}
if (minutes > 0)
{
long leftoverSeconds = seconds % 60;
units.put("seconds", leftoverSeconds);
}
if (seconds > 0)
{
long leftoverMilliseconds = milliseconds % 1000;
units.put("milliseconds", leftoverMilliseconds);
}
elapsed.append(PrependZeroIfNeeded(units.get("days")) + " days ")
.append(PrependZeroIfNeeded(units.get("hours")) + " hours ")
.append(PrependZeroIfNeeded(units.get("minutes")) + " minutes ")
.append(PrependZeroIfNeeded(units.get("seconds")) + " seconds ")
.append(PrependZeroIfNeeded(units.get("milliseconds")) + " ms");
return elapsed.toString();
}
private static String PrependZeroIfNeeded(long aValue)
{
return aValue < 10 ? "0" + aValue : Long.toString(aValue);
}
和一个测试类:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import junit.framework.TestCase;
public class TimeUtilsTest extends TestCase
{
public void testGetElapsed()
{
long start = System.currentTimeMillis();
GregorianCalendar calendar = (GregorianCalendar) Calendar.getInstance();
calendar.setTime(new Date(start));
calendar.add(Calendar.MILLISECOND, 610);
calendar.add(Calendar.SECOND, 35);
calendar.add(Calendar.MINUTE, 5);
calendar.add(Calendar.DAY_OF_YEAR, 5);
long end = calendar.getTimeInMillis();
assertEquals("05 days 00 hours 05 minutes 35 seconds 610 ms", TimeUtils.GetElapsed(start, end, true));
}
}
如果目的只是将粗略的计时信息打印到程序日志中,那么Java项目的简单解决方案不是编写自己的秒表或计时器类,而是使用Apache Commons Lang中的org.apache.commons.lang.time.StopWatch类。
final StopWatch stopwatch = new StopWatch();
stopwatch.start();
LOGGER.debug("Starting long calculations: {}", stopwatch);
...
LOGGER.debug("Time after key part of calcuation: {}", stopwatch);
...
LOGGER.debug("Finished calculating {}", stopwatch);
你的新类:
public class TimeWatch {
long starts;
public static TimeWatch start() {
return new TimeWatch();
}
private TimeWatch() {
reset();
}
public TimeWatch reset() {
starts = System.currentTimeMillis();
return this;
}
public long time() {
long ends = System.currentTimeMillis();
return ends - starts;
}
public long time(TimeUnit unit) {
return unit.convert(time(), TimeUnit.MILLISECONDS);
}
}
用法:
TimeWatch watch = TimeWatch.start();
// do something
long passedTimeInMs = watch.time();
long passedTimeInSeconds = watch.time(TimeUnit.SECONDS);
之后,所经过的时间可以转换为任何你喜欢的格式,例如日历
Greetz, 查德
我发现这段代码在计时时很有用:
public class Et {
public Et() {
reset();
}
public void reset() {
t0=System.nanoTime();
}
public long t0() {
return t0;
}
public long dt() {
return System.nanoTime()-t0();
}
public double etms() {
return etms(dt());
}
@Override public String toString() {
return etms()+" ms.";
}
public static double etms(long dt) {
return dt/1000000.; // 1_000_000. breaks cobertura
}
private Long t0;
}
不幸的是,目前发布的十个答案中没有一个是完全正确的。
如果您正在测量经过的时间,并且希望它是正确的,那么必须使用System.nanoTime()。您不能使用System.currentTimeMillis(),除非您不介意结果是错误的。
The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.
由于nanoTime的目的是测量经过的时间,因此它不受任何这些小修正的影响。它是你想要使用的。当前使用currentTimeMillis进行的任何计时都将关闭——甚至可能为负值。
您可能会说,“这听起来似乎并没有那么重要”,对此我说,也许不是,但总的来说,正确的代码不就是比错误的代码好吗?此外,nanoTime打字时间更短。
之前发布的关于nanoTime通常只有微秒精度的免责声明是有效的。此外,它可能需要超过一微秒的时间来调用,这取决于环境(另一个也是如此),所以不要期望对非常非常小的间隔进行正确的计时。