[PYTHON] Implemented various yes commands

Start

I happened to read an article about the yes command, so I gave it a try. A little story about the Unix command "yes"|Computer Science| POSTD I don't lock the standard input. If it is a print function, support for variable arguments seems to be an obstacle, so basically write is used.

For the time being

Built-in yes command for my Arch Linux (GNU coreutils 8.29)

$ yes | pv -r > /dev/null

About ** 8.63 GiB / s **

C I haven't put any optimization in gcc (7.3.0)

No buffer

#include <unistd.h>

#define LEN 2

int main() {

    char yes[LEN] = "y\n";

    while (1) {
        write(1, yes, LEN);
    }
}

About ** 4.44 MiB / s ** Slower than I expected

With buffer (8KB)

#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE 8192
#define LEN 2

int main() {
    char *buf = malloc(BUFSIZE);

    int i;
    char yes[LEN] = "y\n";

    for (i = 0; i < BUFSIZE; i += LEN) {
        memcpy(buf + i, yes, sizeof(char) * LEN);
    }

    while (1) {
        write(1, buf, BUFSIZE);
    }
}

About ** 8.85 GiB / s ** ~~ Oh, it's like writing to a strange memory ~~ I think it's because of the buffer size that it's a little faster than the built-in yes.

Python 3.6.4

No buffer

import sys

while True:
    sys.stdout.write('y\n')

About ** 14.2MiB / s ** Faster than no C buffer

With buffer (8KB)

import sys

BUF_SIZE = 8192

yes = ''
while len(yes) <= BUF_SIZE:
    yes += 'y\n'

while True:
    sys.stdout.write(yes)

About ** 4.07 GiB / s ** Quite fast for the interpreter

~~ Favorite ~~ I tried it with a shell script

No buffer

$ while true; do echo y; done | pv -r > /dev/null 

About ** 890 KiB / s **

With buffer (8KB file)

$ for i in `seq 4096`; do echo y; done > yes8kb.txt; while true; do cat yes8kb.txt; done | pv -r > /dev/null

About ** 2.93 MiB / s **

Forcibly (I made a 1GB file and tried it)

$ for i in `seq 524288`; do echo y; done > yes1mb.txt; for i in `seq 1024`; do cat yes1mb.txt; done > yes1g.txt; while true; do cat yes1g.txt; done | pv -r > /dev/null

*** 4.93 GiB / s ***

Impressions

~~ Shell script ~~ cat command is doing well There seems to be a better way to write

Recommended Posts

Implemented various yes commands
Various Linux commands
[Linux Mint 20] Various WiFi confirmation commands