0

The following simple program is 100x faster when directed to /dev/null:

#include <stdio.h>
int main(int argc, char **argv)
{
    for (int i=0;i<10000000;i++) { printf("%d\n",i); }
    return 0;
}

How can I find where exactly the speedup comes from?

$ gcc -O0 main.c -o main
$ ./main
$ ./main >/dev/null
$ ./main > output.txt

EDIT: redirecting to a file is 100x faster too. so I guess /dev/null is exactly like any other file?

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 1
    What about output to a file? – DaBler Dec 21 '20 at 12:38
  • 1
    Why is this tagged [tag:bash]? Also, why do you compile with `-O0` if you want something to be as fast as possible? – Ted Lyngmo Dec 21 '20 at 12:43
  • @DaBler I'll add that to the post ... it's 100x faster too – OrenIshShalom Dec 21 '20 at 12:43
  • I compiled with `-O0` to make sure that this whole loop will not disappear into thin air ... – OrenIshShalom Dec 21 '20 at 12:44
  • @OrenIshShalom The compiler isn't allowed to make it disappear into thin air because that would change observable effects of the program. – Ted Lyngmo Dec 21 '20 at 12:45
  • 1
    I guess a better question is: `is redirection to /dev/null the same as redirection to an arbitrary file` ... – OrenIshShalom Dec 21 '20 at 12:49
  • 1
    @OrenIshShalom Yes, it is after all a [device file](https://en.m.wikipedia.org/wiki/Device_file#Character_devices) – Nick is tired Dec 21 '20 at 12:53
  • 1
    printing 10 million lines to stdout is always going to be slow; think about what has to be done to print a line to a 'window', redrawing the window to shift lines up, etc, etc, etc ... **tons** of time to do that for 10 million iterations; minimizing the window may help speed up the process, some, but the console is still having to process/display 10 million lines of output; all of this overhead to 'display' 10 million lines goes away when writing to a file (or /dev/null) – markp-fuso Dec 21 '20 at 13:00
  • 1
    Other "arbitrary" files involve synchronizing with whichever medium you are writing to; if it is slower than your write rate, you will be blocking to wait for the I/O buffers to clear. With `/dev/null` obviously the output buffer will be instantaneously cleared. – tripleee Dec 21 '20 at 13:06

1 Answers1

2

Uh, because printing to the terminal is slow? Try it over a 300 baud connection!

tripleee
  • 175,061
  • 34
  • 275
  • 318