简体   繁体   English

使用 fflush 加速代码以防止超出时间限制

[英]Using fflush for speeding up code to prevent a time limit exceeded

The following code gets TLE (time limit exceeded) if the standard output is not flushed.如果未刷新标准 output,则以下代码将获得 TLE(超出时间限制)。

#include<stdio.h>
int main(){
    int a;
    while(1){
        scanf("%d",&a);
        printf("%d\n",a);
        fflush(stdout);
        if(a==42)
            break;
    }
    return 0;
}

How does flushing the output buffer help to overcome TLE?刷新 output 缓冲区如何帮助克服 TLE?
This is the problem link - https://www.spoj.com/problems/EXPECT/这是问题链接 - https://www.spoj.com/problems/EXPECT/

The problem specification tells you what to do:问题规范告诉您该怎么做:

Attention: the program should clear the output buffer after printing each line.注意:程序在打印每一行后都应该清除 output 缓冲区。

It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout).可以使用 fflush(stdout) 命令或在执行开始时设置适当的缓冲类型 - setlinebuf(stdout) 来完成。

The problem title indicates why:问题标题说明了原因:

(Interactive) (交互的)

The judging software is operating the program interactively .评判软件以交互方式运行程序。 After giving the program an input, it waits for output before providing more input.给程序一个输入后,它会等待 output 再提供更多输入。 When your program does not flush the buffered output, the judging software keeps waiting until its time limit is exceeded.当您的程序没有刷新缓冲的 output 时,判断软件会一直等待,直到超过其时间限制。

Commonly, output streams to terminals are line-buffered, in which case printing a new-line character causes them to be flushed.通常,到终端的 output 流是行缓冲的,在这种情况下,打印换行符会导致它们被刷新。 However, this judging software is likely using a pipe that is fully buffered, so output will not be flushed until the buffer is full or you explicitly request a flush (or, at the start of the program, you change the buffering mode to unbuffered or line-buffered).但是,这个判断软件很可能使用的是完全缓冲的 pipe,所以 output 不会被刷新,直到缓冲区已满或您明确请求刷新(或者,在程序开始时,您将缓冲模式更改为无缓冲或行缓冲)。

When you flush the output, the judging software will see it, and then it will continue and provide more input.当你刷output时,判断软件会看到,然后继续提供更多输入。

As an alternative to flushing the output after each printf , you can set the stream to line buffering mode by executing setvbuf(stdout, NULL, _IOLBF, 0); As an alternative to flushing the output after each printf , you can set the stream to line buffering mode by executing setvbuf(stdout, NULL, _IOLBF, 0); at the beginning of the program (before doing any other operation on the stream).在程序开始时(在对流进行任何其他操作之前)。

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

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