繁体   English   中英

为什么使用 System.out.printf() 而不是 System.out.println() 会导致超出时间限制?

[英]Why using System.out.printf() instead of System.out.println() causes Time Limit Exceeded?

最近我正在解决一个关于 codeforces的问题。 在最后对其解决方案进行编码时,我必须从我使用的二维数组中打印值,

for (int p = 0; p < m; p++) {
    if (positions[edges[p][0]-1] < positions[edges[p][1]-1]) {
        System.out.printf("%d %d\n", edges[p][0], edges[p][1]);
    } else {
        System.out.printf("%d %d\n", edges[p][1], edges[p][0]);
    }
}

使用上述方法导致测试用例超出时间限制。 虽然我将上面的代码替换为如下代码,但它确实有效。

for (int p = 0; p < m; p++) {
    if (positions[edges[p][0]-1] < positions[edges[p][1]-1]) {
        System.out.println((edges[p][0]) + " " + (edges[p][1]));
    } else {
        System.out.println((edges[p][1]) + " " + (edges[p][0]));
    }
}

是什么原因造成的?

我提交的复制在这里

我创建了一个简单的测试(当然它不是基准,但它可以简单地给出一些结论):

public static void main(String[] args) {
    long beforePrintln = System.nanoTime();
    int a = 1;
    int b = 2;
    for (int i = 0; i < 1000000; i++) {
        System.out.println(a + " string " + b);
    }
    long beforePrintf = System.nanoTime();
    for (int i = 0; i < 1000000; i++) {
        System.out.printf("%d string %d\n", a, b);
    }
    long after = System.nanoTime();
    System.out.println();
    System.out.println(beforePrintf - beforePrintln);
    System.out.println(after - beforePrintf);
}

结果是(我多次运行它,结果总是几乎相同):

4796301400
9976818400

似乎 printf (带有字符串格式)比带有字符串连接的 println 慢 2 倍。 我认为 printf 较慢,因为它在格式化 output 方面比仅打印给定行的简单 println 更强大。

暂无
暂无

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

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