(dis)优点循环中使用的不同写入方法

时间:2018-01-28 16:07:30

标签: linux algorithm filesystems fwrite

我正在用C编写一个程序(尽管这个问题适用于其他语言),它将在循环中运行并且每次都将输出写入文件。我可以看到5种不同的方法。

我想知道每种方法的(dis)优势是什么,并且特别感兴趣的是Linux作为操作系统和btrfs作为文件系统(但不要害怕回答其他文件系统/操作系统组合)。

  • createstring()是一个将创建当前要写入的数据的函数。为简单起见,我假设只需要纳秒

  • SLEEPDURATION_IN_MSEVERY_X_BYTES是您可以选择的常量,以便更改优点/缺点,FILENAME只是一个包含文件路径的字符串

我对磁盘活动(i.d.磁盘使用寿命缩短),代码崩溃时的安全性,速度,EVERY_X_BYTES的最佳设置(取决于SLEEPDURATION_IN_MS)感兴趣,...

如果你能想到其他方法也很好......

    //method 1: open, append and close constantly
    while(1) {
            char *some_string = createstring();
            FILE* some_file = fopen(FILENAME, "a");
            fprintf(some_file, "%s", some_string);
            free(some_string);
            fclose(some_file);
            usleep(SLEEPDURATION_IN_MS);
    }

    //method 2: open once, append constantly, let the system decide to sync
    FILE* some_file = fopen(FILENAME, "a");
    while(1) {
            char *some_string = createstring();
            fprintf(some_file, "%s", some_string);
            free(some_string);
            usleep(SLEEPDURATION_IN_MS);
    }

    //method 3: open once, append and sync everytime
    FILE* some_file = fopen(FILENAME, "a");
    while(1) {
            char *some_string = createstring();
            fprintf(some_file, "%s", some_string);
            free(some_string);
            fflush(some_file);
            usleep(SLEEPDURATION_IN_MS);
    }

    //method 4: open once, append every time, sync sometimes
    FILE* some_file = fopen(FILENAME, "a");
    int bytecount=0;
    while(1) {
            char *some_string = createstring();
            bytecount += strlen(some_string);
            fprintf(some_file, "%s", some_string);
            free(some_string);
            if(bytecount >= EVERY_X_BYTES) {
                    fflush(some_file);
                    bytecount=0;
            }
            usleep(SLEEPDURATION_IN_MS);
    }

    //method 5: open once, save in memory, append and sync sometimes
    FILE* some_file = fopen(FILENAME, "a");
    char *mem;
    char *oldmem = strdup("");
    while(1) {
            char *some_string = createstring();
            asprintf(&mem, "%s%s", oldmem, some_string);
            free(oldmem); free(some_string);
            if(strlen(mem) >= EVERY_X_BYTES) {
                    fprintf(some_file, "%s", mem);
                    fflush(some_file);
                    free(mem);
                    oldmem = strdup("");
            } else {
                    oldmem = mem;
            }
            usleep(SLEEPDURATION_IN_MS);
    }

0 个答案:

没有答案