我想要这样的东西:

public class Stream
{
    public startTime;
    public endTime;

    public getDuration()
    {
        return startTime - endTime;
    }
}

同样重要的是,例如,如果startTime是23:00,endTime是1:00,则持续时间为2:00。

为了在Java中实现这一点,应该使用哪些类型?


当前回答

Java提供了静态方法System.currentTimeMillis()。这返回一个长值,所以这是一个很好的参考。很多其他类也接受'timeInMillis'形参,这个形参也很长。

许多人发现使用Joda Time库更容易计算日期和时间。

其他回答

如果您正在编写一个必须处理持续时间的应用程序,那么请查看Joda-Time,它有专门处理持续时间、间隔和周期的类。你的getDuration()方法看起来可以返回一个Joda-Time Interval:

DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);

public Interval getInterval() {
    Interval interval = new Interval(start, end);
}

为了在Java中实现这一点,应该使用哪些类型?

简短的回答是长。现在,更多关于如何衡量……

System.currentTimeMillis()

“传统”的方法是使用System.currentTimeMillis():

long startTime = System.currentTimeMillis();
// ... do something ...
long estimatedTime = System.currentTimeMillis() - startTime;

o.a.c.l.t.StopWatch

注意,Commons Lang有一个StopWatch类,可以用来测量以毫秒为单位的执行时间。它有split(), suspend(), resume()等方法,允许在执行的不同点采取措施,您可能会发现方便。看一看。

System.nanoTime()

如果您正在寻找运行时间的极其精确的度量,您可能更喜欢使用System.nanoTime()。从它的javadoc:

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

Jamon

另一种选择是使用JAMon,这是一种收集start()和stop()方法之间任何代码的统计信息(执行时间、命中次数、平均执行时间、最小值、最大值等)的工具。下面是一个非常简单的例子:

import com.jamonapi.*;
...
Monitor mon=MonitorFactory.start("myFirstMonitor");
...Code Being Timed...
mon.stop();

查看www.javaperformancetunning.com上的这篇文章,有很好的介绍。

使用AOP

最后,如果您不想让这些度量使您的代码变得混乱(或者如果您不能更改现有的代码),那么AOP将是一个完美的武器。我不打算深入讨论这个问题但我至少想提一下。

下面是一个使用AspectJ和JAMon的非常简单的方面(这里,切入点的短名称将用于JAMon监视器,因此调用thisJoinPoint.toShortString()):

public aspect MonitorAspect {
    pointcut monitor() : execution(* *.ClassToMonitor.methodToMonitor(..));

    Object arround() : monitor() {
        Monitor monitor = MonitorFactory.start(thisJoinPoint.toShortString());
        Object returnedObject = proceed();
        monitor.stop();
        return returnedObject;
    }
}

切入点定义可以很容易地调整为基于类名、包名、方法名或它们的任何组合来监视任何方法。度量实际上是AOP的一个完美用例。

如果目的只是将粗略的计时信息打印到程序日志中,那么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);

如果你喜欢使用Java的日历API,你可以试试这个,

Date startingTime = Calendar.getInstance().getTime();
//later on
Date now = Calendar.getInstance().getTime();
long timeElapsed = now.getTime() - startingTime.getTime();

Java提供了静态方法System.currentTimeMillis()。这返回一个长值,所以这是一个很好的参考。很多其他类也接受'timeInMillis'形参,这个形参也很长。

许多人发现使用Joda Time库更容易计算日期和时间。