public class Main {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        long startTime2 = System.currentTimeMillis();
        for (int i = -1; ++i < 1000; ) {
            String row = "Column 1: " + "1" + ",  Column 2: " + "2" +
                    ",  Column 3: " + "3" + ",  Column 3: " + "4";
            System.out.println(row);
        }
        long endTime = System.nanoTime();
        long endTime2 = System.currentTimeMillis();

        long durationInMillis = (endTime - startTime) / 1_000_000;
        long durationInMillis2 = (endTime2 - startTime2) / 1;
        System.out.println("Time taken to output the result: " + durationInMillis + " milliseconds");
        System.out.println("Time taken to output the result: " + durationInMillis2 + " milliseconds");
    }
}


idea
点击运行

Time taken to output the result: 6 milliseconds
Time taken to output the result: 6 milliseconds


cmd 命令提示符
java Main.java

Time taken to output the result: 143 milliseconds
Time taken to output the result: 145 milliseconds
举报· 186 次点击
登录 注册 站外分享
9 条回复  
lucasj 初学 2024-8-24 10:43:49
可能运行参数不一样。idea 运行加了一堆 jvm 参数
mightybruce 小成 2024-8-24 11:00:35
在控制台运行包含 jit 编译吧, 这个时间这么长 只有编译才需要这么久。
FrankAdler 小成 2024-8-24 12:46:37
你 hold 主进程不退出,看下 idea 实际执行的可能是编译后的
kneo 小成 2024-8-24 13:07:39
命令行先编译再执行。
chendy 初学 2024-8-24 13:08:59
因为一样是 System.out.println ,打印到不同的地方耗时不一样,至于为什么不一样我就解释不出来了(可以问问 ai ?)
我这里把 1000 改成 10000
idea 执行 82
命令行 1452
命令行重定向到文件 55
不打印到屏幕上还是更快
leconio 小成 2024-8-24 14:23:41
idea 不是默认 jbr 吗,你本地啥运行时。
RecursiveG 小成 2024-8-24 15:22:14
你重定向到文件试试
orioleq 小成 2024-8-24 17:04:52
@kneo 你这回的是啥…人家问的和打印的都是执行时间
seanzxx 小成 2024-8-25 02:37:28
你大量的文字输出,是在测试终端的处理和渲染的性能。
IDEA 的结果输出,只需要输出程序的控制台输出,可以简单的处理成输出到一个 buffer 或者文件,再输出到窗口,速度快是自然的。
终端 (Terminal) 复杂得多,举个简单的例子,它需要处理键盘输入,你还可以用 Ctrl + C 终端程序运行。
IntelliJ 里面带有完整功能 Terminal 界面的就慢很多。

在我的 MacBook 上, 这个代码在相同的 JDK 中耗费的时间是 (我把代码的 for 循环从 1000 改成了 10000 ,不然看不出差距):

IDEA 的 run:
Time taken to output the result: 25 milliseconds
Time taken to output the result: 26 milliseconds

IDEA 的 terminal:
Time taken to output the result: 188 milliseconds
Time taken to output the result: 188 milliseconds

MacOS 原生的 Terminal:
Time taken to output the result: 32 milliseconds
Time taken to output the result: 33 milliseconds

kitty(一个第三方 terminal 程序,使用了 GPU 加速,一般认为比系统自带的终端快):
Time taken to output the result: 29 milliseconds
Time taken to output the result: 30 milliseconds
返回顶部