Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中度量所用的时间?_Java_Time - Fatal编程技术网

如何在Java中度量所用的时间?

如何在Java中度量所用的时间?,java,time,Java,Time,我想要这样的东西: public class Stream { public startTime; public endTime; public getDuration() { return startTime - endTime; } } 同样重要的是,如果开始时间为23:00,结束时间为1:00,则持续时间为2:00 要在Java中实现这一点,需要使用哪些类型?如果您是从System.currentTimeMillis()获取时间戳

我想要这样的东西:

public class Stream
{
    public startTime;
    public endTime;

    public getDuration()
    {
        return startTime - endTime;
    }
}
同样重要的是,如果开始时间为23:00,结束时间为1:00,则持续时间为2:00


要在Java中实现这一点,需要使用哪些类型?

如果您是从
System.currentTimeMillis()
获取时间戳,那么您的时间变量应该是长的。

Java提供了静态方法
System.currentTimeMillis()
。这将返回一个长值,因此它是一个很好的参考。许多其他类接受同样长的“timeInMillis”参数

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

您的新课程:

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);
  Stream s = .... 

  s.start();

  // do something for a while 

  s.stop();

  s.getDuration(); // gives the elapsed time in milliseconds. 
之后,您可以使用日历等工具将经过的时间转换为您喜欢的任何格式

格里茨,
GHad

如果您更喜欢使用Java,可以试试这个

Date startingTime = Calendar.getInstance().getTime();
//later on
Date now = Calendar.getInstance().getTime();
long timeElapsed = now.getTime() - startingTime.getTime();
为了在Java中实现这一点,需要使用哪些类型

回答:长

public class Stream {
    public long startTime;
    public long endTime;

    public long getDuration() {
        return endTime - startTime;
    }
    // I  would add
    public void start() {
        startTime = System.currentTimeMillis();
    }
    public void stop() {
         endTime = System.currentTimeMillis();
     }
}
用法:

    TimeWatch watch = TimeWatch.start();
    // do something
    long passedTimeInMs = watch.time();
    long passedTimeInSeconds = watch.time(TimeUnit.SECONDS);
  Stream s = .... 

  s.start();

  // do something for a while 

  s.stop();

  s.getDuration(); // gives the elapsed time in milliseconds. 
这是我对你第一个问题的直接回答

关于最后一个“注意事项”,我建议你使用乔达时间。它包含一个适合您需要的类

为了在Java中实现这一点,需要使用哪些类型

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

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

o、 a.c.l.t.秒表 注意,Commons Lang有一个类,可以用来测量以毫秒为单位的执行时间。它有诸如、、等方法,允许在不同的执行点进行测量,您可能会觉得很方便。看一看

System.nanoTime() 如果您希望对经过的时间进行极其精确的测量,则可能更愿意使用。从其javadoc:

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;
杰蒙 另一种选择是使用一种工具,它可以为start()和stop()方法之间的任何代码收集统计信息(执行时间、命中次数、平均执行时间、最小值、最大值等)。下面是一个非常简单的示例:

import com.jamonapi.*;
...
Monitor mon=MonitorFactory.start("myFirstMonitor");
...Code Being Timed...
mon.stop();
请访问www.javaperformancetuning.com以获得一个很好的介绍

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

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


切入点定义可以很容易地根据类名、包名、方法名或它们的任意组合来监视任何方法。度量确实是AOP的完美用例。

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

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项目的简单解决方案不是编写自己的秒表或计时器类,而是使用Apache Commons Lang中的类

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);

值得注意的是

  • System.currentTimeMillis()最多只有毫秒精度。在某些windows系统上,其可用时间为16毫秒。替代品小于200纳秒的成本较低
  • System.nanoTime()在大多数系统上的精度仅为微秒,在windows系统上可以跳100微秒(即有时不如看上去的那么精确)
  • 日历是一种非常昂贵的计算时间的方法。(除了XMLGregorianCalendar之外,我还可以想到)有时候这是最合适的解决方案,但请注意,您应该只花很长的时间间隔

不幸的是,目前发布的十个答案中没有一个是完全正确的


如果要测量经过的时间,并且希望它是正确的,则必须使用
System.nanoTime()
。您不能使用
System.currentTimeMillis()
,除非您不介意结果出错

nanoTime
的目的是测量经过的时间,而
currentTimeMillis
的目的是测量挂钟时间。你不能把这个用于其他目的。原因是没有一台计算机的时钟是完美的;它总是漂移,偶尔需要纠正。这种校正可以手动进行,或者在大多数机器的情况下,有一个进程运行并不断对系统时钟(“挂钟”)进行小的校正。这种情况经常发生。每当出现闰秒时,就会发生另一次这样的修正

由于
nanoTime
的目的是测量经过的时间,因此它不受任何这些小修正的影响。这是你想用的。当前使用
currentTimeMillis
进行的任何计时都将关闭,甚至可能为负值

你可能会说,“这听起来并没有那么重要”,我会说,也许没有,但总的来说,正确的代码不是比错误的代码更好吗?此外,
nanoTime
的输入时间更短

以前发布的关于
nanoTime
的免责声明通常只有微秒精度是有效的。此外,根据具体情况,调用它可能需要一整微秒以上的时间(另一种情况也是如此),因此不要期望非常小的时间间隔正确。

tl;博士 例如,如果开始时间为23:00,结束时间为1:00,则持续时间为2:00

不可能。如果你只有一天中的时间,时钟会在午夜停止。如果没有日期的上下文,我们怎么知道你指的是第二天、下周还是下一个十年的凌晨1点

所以从晚上11点到凌晨1点意味着在22小时内倒转时间,运行时钟c的指针
Duration.between(              // Represent a span of time a total number of seconds plus a fractional second in nanoseconds.
    LocalTime.of( 23 , 0 ) ,   // A time-of-day without a date and without a time zone. 
    LocalTime.of( 1 , 0 )      // A time-of-day clock stops at midnight. So getting to 1 AM from 11 PM means going backwards 22 hours.
)                              // Return a `Duration` object.
.toString()                    // Generate a `String` representing this span of time using standard ISO 8601 format: PnYnMnDTnHnMnS
Duration.between(    // Represent a span of time a total number of seconds plus a fractional second in nanoseconds.
    then ,           // Some other `Instant` object, captured earlier with `Instant.now()`.
    Instant.now()    // Capture the current moment in UTC with a resolution as fine as nanoseconds, depending on the limits of your host computer hardware clock and operating system. Generally you will get current moment in microseconds (six decimal digits of fractional second) in Java 9, 10, and 11, but only milliseconds in Java 8. 
)                    // Return a `Duration` object.
.toString()          // Generate a `String` representing this span of time using standard ISO 8601 format: PnYnMnDTnHnMnS
LocalTime sooner = LocalTime.of ( 17, 00 );
LocalTime later = LocalTime.of ( 19, 00 );
Duration duration = Duration.between ( sooner, later );
System.out.println ( "sooner: " + sooner + " | later: " + later + " | duration: " + duration );
LocalTime sooner = LocalTime.of ( 23, 0 );
LocalTime later = LocalTime.of ( 1, 0 );
LocalDate localDate = LocalDate.of ( 2016, 1, 23 );
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime sooner = ZonedDateTime.of ( localDate, LocalTime.of ( 23, 0 ), zoneId );
ZonedDateTime later = ZonedDateTime.of ( localDate.plusDays ( 1 ), LocalTime.of ( 1, 0 ), zoneId );
Duration duration = Duration.between ( sooner, later );
System.out.println ( "sooner: " + sooner + " | later: " + later + " | duration: " + duration );
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;
}
SimpleDateFormat format = new SimpleDateFormat("HH:mm");

Date d1 = format.parse(strStartTime);
Date d2 = format.parse(strEndTime);

long diff = d2.getTime() - d1.getTime();
long diffSeconds,diffMinutes,diffHours;

if (diff > 0) {
diffSeconds = diff / 1000 % 60;
diffMinutes = diff / (60 * 1000) % 60;
diffHours = diff / (60 * 60 * 1000);
}
else{
long diffpos = (24*((60 * 60 * 1000))) + diff;
diffSeconds = diffpos / 1000 % 60;
diffMinutes = diffpos / (60 * 1000) % 60;
diffHours = (diffpos / (60 * 60 * 1000));
}
Byte Stream Reader Elapsed Time for 23.7 MB is 96 secs

import java.io.*;
import java.io.IOException;
import java.util.Scanner;

class ElaspedTimetoCopyAFileUsingByteStream
{

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;


    public void start() 
    {
        this.startTime = System.currentTimeMillis();
        this.running = true;
    }


    public void stop() 
    {
        this.stopTime = System.currentTimeMillis();
        this.running = false;
    }



    public long getElapsedTime() 
    {
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed;
    }



    public long getElapsedTimeSecs()                 
    {
        long elapsed;
        if (running) 
        {
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
        }
        else
        {
            elapsed = ((stopTime - startTime) / 1000);
        }
        return elapsed;
    }





    public static void main(String[] args) throws IOException
    {
        ElaspedTimetoCopyAFileUsingByteStream  s = new ElaspedTimetoCopyAFileUsingByteStream();
        s.start();

        FileInputStream in = null;
        FileOutputStream out = null;

      try {
         in = new FileInputStream("vowels.txt");   // 23.7  MB File
         out = new FileOutputStream("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }



        s.stop();
        System.out.println("elapsed time in seconds: " + s.getElapsedTimeSecs());
    }
}

[Elapsed Time for Byte Stream Reader][1]

**Character Stream Reader Elapsed Time for 23.7 MB is 3 secs**

import java.io.*;
import java.io.IOException;
import java.util.Scanner;

class ElaspedTimetoCopyAFileUsingCharacterStream
{

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;


    public void start() 
    {
        this.startTime = System.currentTimeMillis();
        this.running = true;
    }


    public void stop() 
    {
        this.stopTime = System.currentTimeMillis();
        this.running = false;
    }



    public long getElapsedTime() 
    {
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed;
    }



    public long getElapsedTimeSecs()                 
    {
        long elapsed;
        if (running) 
        {
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
        }
        else
        {
            elapsed = ((stopTime - startTime) / 1000);
        }
        return elapsed;
    }





    public static void main(String[] args) throws IOException
    {
        ElaspedTimetoCopyAFileUsingCharacterStream  s = new ElaspedTimetoCopyAFileUsingCharacterStream();
        s.start();

         FileReader in = null;                // CharacterStream Reader
      FileWriter out = null;

      try {
         in = new FileReader("vowels.txt");    // 23.7 MB
         out = new FileWriter("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }

              s.stop();
        System.out.println("elapsed time in seconds: " + s.getElapsedTimeSecs());
    }
}


[Elapsed Time for Character Stream Reader][2]


  [1]: https://i.stack.imgur.com/hYo8y.png
  [2]: https://i.stack.imgur.com/xPjCK.png
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));

  }

}