miriam_e: from my drawing MoonGirl (Default)
[personal profile] miriam_e
I asked KimiAI if it could write a C program to repeat a string n times. I am a crappy C programmer. (I need to fix that shortcoming.) This program is optimised for just this task and beats all the hacks from my previous post, by a big margin.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>

int main(int argc, char *argv[]) {
    if (argc != 3) return 1;
    
    const char *str = argv[1];
    int n = atoi(argv[2]);
    size_t len = strlen(str);
    
    if (n <= 0) return 0;
    
    // Use write() directly with a large buffer
    size_t unit = len + 1;
    size_t total = unit * n;
    char *buf = malloc(total);
    
    for (int i = 0; i < n; i++) {
        memcpy(buf + i*unit, str, len);
        buf[i*unit + len] = (i == n-1) ? '\n' : ' ';
    }
    
    // Single syscall, no stdio overhead
    write(STDOUT_FILENO, buf, total);
    
    free(buf);
    return 0;
}
And compile with optimisations:
gcc -O3 -o repeat repeat.c
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

miriam_e: from my drawing MoonGirl (Default)
miriam_e

February 2026

S M T W T F S
123 4 567
891011121314
15161718192021
22232425262728

Style Credit

Expand Cut Tags

No cut tags
Page generated Thursday, 5 February 2026 07:40 am
Powered by Dreamwidth Studios