JVM 不确定的运行时间

发布于 2024-12-10 00:23:53 字数 567 浏览 1 评论 0原文

在 2.8 GHz Linux 计算机上,运行 5 亿次迭代的循环的单线程程序通常需要大约 400 毫秒,有时大约需要 1200 毫秒。这是在一个除了测量循环所用时间之外不执行任何其他操作的程序中观察到的。是什么导致了这种变化?

import java.io.PrintWriter;
import java.util.Date;

public class Tester
{
    public static void main(String[] args)
    {
        PrintWriter pw = new PrintWriter(System.out, true);

        Date d0 = new Date();
        long t0 = d0.getTime();

        for (long i = 0; i < 500000000; i++)
            ;

        Date d1 = new Date();
        long t1 = d1.getTime();

        pw.format("%d\n", t1 - t0);   
    }
}

A single threaded program running a loop of 500 million iterations takes usually about 400 ms and occasionally about 1200 ms on a 2.8 GHz linux computer. This is observed in a program that does nothing else but measure the elapsed time of the loop. What accounts for this variability?

import java.io.PrintWriter;
import java.util.Date;

public class Tester
{
    public static void main(String[] args)
    {
        PrintWriter pw = new PrintWriter(System.out, true);

        Date d0 = new Date();
        long t0 = d0.getTime();

        for (long i = 0; i < 500000000; i++)
            ;

        Date d1 = new Date();
        long t1 = d1.getTime();

        pw.format("%d\n", t1 - t0);   
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

中性美 2024-12-17 00:23:53

即使没有垃圾要收集,垃圾收集例程也需要运行一段时间。

很容易假设,由于您不分配或取消引用内存,因此您将不需要收集垃圾;但是,垃圾收集例程在独立线程中运行,并且不会检查代码中可能的流程来确定它是否应该运行。

因此,垃圾收集例程启动并发现没有垃圾可以收集。这需要一些时间。

此外,您的程序(即解释您的类的整个 JVM)可能因操作系统需要立即处理某些中断而从 CPU 中交换出来。这种情况甚至可能发生在多核系统中,具体取决于 CPU 的核心选择算法。 CPU 必须立即处理的项目示例包括将以太网内存缓冲区复制到系统内存(以防止丢包)、捕获键盘输入等。

简而言之,如果您希望分析有意义,则必须对您的数据进行真正的统计。基准测试,因为各种外部项目都会影响您运行程序的时间。

The garbage collections routines need to run some time, even if you don't have garbage to collect.

It is easy to assume that since you don't allocate or dereference memory then you will not need to collect garbage; however, the garbage collection routine is running in an independent thread and does not inspect the possible flows through your code to determine if it should run.

So, the garbage collection routine launches and finds no garbage to collect. That takes some time.

In addition, your program (that is, the entire JVM interpreting your classes) may have been swapped off the CPU by the operating system's need to immediately handle some interrupt. This can even happen in multi-core systems, depending on the CPU's core selection algorithms. Examples of items that the CPU must handle immediately include copying Ethernet memory buffers into system memory (to prevent dropped packets), capturing keyboard input, etc.

In short, if you want your analysis to mean something, you have to do real statistics on your benchmarking, as all sorts of external items can impact your running program's time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文