简体   繁体   English

尝试在 Java 中测量经过的时间

[英]Trying to measure elapsed time in Java

I was unable to get the Java clock to measure the time elapsed in milliseconds from the beginning to the end of a simple program.我无法让 Java 时钟来测量从一个简单程序的开始到结束所经过的时间(以毫秒为单位)。

I've copied the program below.我已经复制了下面的程序。 You will see that I used the utility Calendar, then printed the time before and after the loop.您将看到我使用了实用程序 Calendar,然后打印了循环前后的时间。 No matter how long the loop takes, the time shown by the print command before and after the loop does not change.无论循环多长时间,循环前后打印命令显示的时间都不会改变。

Can you suggest a solution?你能提出一个解决方案吗?

I use DrJava.我使用 DrJava。

import java.util.Calendar;

class time
{
  public static void main(String[] args)
  {

    int sum=0;
    int i=0;
    int j=0;
    int n=300;

    Calendar cal = Calendar.getInstance();

    System.out.println("Current milliseconds since 13 Oct, 2008 are :" + cal.getTimeInMillis());

    for (i=0;i < n; i++)
    {
      sum++;
      System.out.println("ROW " + i);  
    }

    System.out.println(" Current milliseconds since 13 Oct, 2008 are :" + cal.getTimeInMillis());
  } 
}

Use

System.nanoTime();

To measure elapsed time.测量经过的时间。

This is available since Java 1.5, monotonic (where possible, method details ).这从 Java 1.5 开始可用,单调(在可能的情况下, 方法详细信息)。

If you want precise measurements of elapsed time, use System.nanoTime() .如果您想要精确测量经过的时间,请使用System.nanoTime()

From the Java Documentation:从 Java 文档:

 public static long nanoTime()

Returns the current value of the most precise available system timer, in nanoseconds.返回最精确的可用系统计时器的当前值,以纳秒为单位。

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.此方法只能用于测量经过的时间,与系统或挂钟时间的任何其他概念无关。 The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative).返回的值表示自某个固定但任意的时间以来的纳秒(可能在未来,因此值可能为负)。 This method provides nanosecond precision, but not necessarily nanosecond accuracy.此方法提供纳秒精度,但不一定提供纳秒精度。 No guarantees are made about how frequently values change.不保证值的更改频率。 Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.由于数值溢出,跨越大约 292 年(263 纳秒)的连续调用之间的差异将无法准确计算经过的时间。

For example, to measure how long some code takes to execute:例如,要测量执行某些代码所需的时间:

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

From the docs:从文档:

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

You have to get a new instance after the loop, and get that instance's time in milliseconds.您必须在循环后获取一个新实例,并以毫秒为单位获取实例的时间。

Also, 300 iterations of a simple loop isn't likely to register any time at all, even if measured in milliseconds.此外,一个简单循环的 300 次迭代根本不可能在任何时间注册,即使以毫秒为单位。 You might want to try 300 thousand (300000) iterations or more.您可能想要尝试 30 万 (300000) 次或更多次迭代。

Also note that even if getTimeInMillis() returns a particular number of milliseconds, be aware that it's probably not updated that frequently.另请注意,即使getTimeInMillis()返回特定的毫秒数,请注意它可能不会经常更新。 It might only be updated every 10 milliseconds or so (when the system tick happens).它可能只每 10 毫秒左右更新一次(当系统滴答发生时)。 This depends entirely on your operating system implementation.这完全取决于您的操作系统实现。

long start = System.currentTimeMillis();

/*** do stuff***/

double elapsed = (System.currentTimeMillis() - start) / 1000.0;

A bit of clarity about why your choice doesn't work out the way expect.有点清楚为什么你的选择没有按预期的方式工作。

Calendar represents a moment in time, with various locale-dependent operations on it, and not something like a running clockwork. Calendar 代表一个时刻,上面有各种依赖于语言环境的操作,而不是像一个正在运行的时钟。

As Greg suggested, you should do a larger number of iterations.正如 Greg 建议的那样,您应该进行更多的迭代。 His argument is valid - that and statistically speaking, having a larger sample will yield more accurate results (this will eliminate random deviations due to uncontrollable events like gc, enviroment, etc.).他的论点是有效的 - 从统计学上讲,拥有更大的样本会产生更准确的结果(这将消除由于不可控事件(如 gc、环境等)造成的随机偏差)。

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

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