Faster output via Java standard?

In an online judging programming contest, I need to output up to 50000 lines in 1 second through standard output (in addition to reading up to 200000 integers that use the buffer for me) My logic seems to be correct, but I continue to reject my submission for more than 1 second I deleted my code logic and only output a constant string, which still exceeded the time limit

For each line of output, is there anything better than using system out. Println (string s) faster output mode?

Solution

I will use a system out. The print call (or the least meaningful one found through the benchmark) is as follows:

String str = "line1\nline2\nline3\n ...";
System.out.print(str);

Edit:

StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 500000; i++) {
        sb.append(i).append("\n");
    }
    String str = sb.toString();
    long nt = System.nanoTime();
    System.out.print(str);
    nt = System.nanoTime() - nt;
    System.out.print("\nTime(ms): " + (double)nt / 1000000);

sb. Tostring() is not a free operation

The above requires approximately 650 milliseconds of laptops (500000 instead of 50000 requested)

Edit2: there are two other skills. In case the filling time is important:

>Construct a StringBuilder with sufficient capacity > do not append for each line (the following code appends 200 lines each time, for which it uses temp SB1); Content is possible only if each line can be the same Please enjoy

long nt = System.nanoTime();
StringBuilder sb1 = new StringBuilder(400);
for (int i = 0; i < 200; i++) {
    sb1.append("l").append("\n");
}
String strSb1 = sb1.toString();

StringBuilder sb = new StringBuilder(1000000);
for (int i = 0; i < 2500; i++) {
    sb.append(strSb1);
}

System.out.print(sb.toString());
nt = System.nanoTime() - nt;
System.out.print("\nTime(ms): " + (double)nt / 1000000);

In my case, about 500 milliseconds

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>