繁体   English   中英

为什么写入用stdout重新打开的文件更快?

[英]Why it is faster writing a file which is freopened with stdout?

在Windows上执行时,此测试代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <assert.h>

int main() {
    // The clock() function returns an approximation of processor time used by the program.
    // The  value  returned is the CPU time used so far as a clock_t;
    // to get the number of seconds used, divide by CLOCKS_PER_SEC.
    auto buf = new char[1048576]; // 1MB
    auto cache = new char[512 * 1024];

    // initialize the buffer
    for (int i = 0; i < 1048576; ++i)
        buf[i] = i;

    auto fp_reopen = freopen("data_freopen.bin", "wb", stdout);
    assert(fp_reopen != nullptr);
    setvbuf(fp_reopen, cache, _IOLBF, 512 * 1024);
    auto clock_begin = clock();
    for (int i = 0; i < 1000; ++i) {
        auto n = fwrite(buf, 1048576, 1, fp_reopen);
        assert(n == 1);
    }
    fflush(fp_reopen);
    auto clock_end = clock();

#ifdef _WIN32
    freopen("CONOUT$", "w", stdout);
#else
    freopen("/dev/tty", "w", stdout);
#endif

    printf("write with freopen clocks elapsed: %zu\n", clock_end - clock_begin);

    auto fp = fopen("data_fopen.bin", "wb");
    assert(fp != nullptr);
    setvbuf(fp, cache, _IOLBF, 512 * 1024);
    clock_begin = clock();
    for (int i = 0; i < 1000; ++i) {
        auto n = fwrite(buf, 1048576, 1, fp);
        assert(n == 1);
    }
    fflush(fp);
    clock_end = clock();
    fclose(fp);

    printf("write with fopen clocks elapsed: %zu\n", clock_end - clock_begin);
    delete[] buf;
    delete[] cache;
    getchar();
}

产生以下结果:

  • write with freopen clocks elapsed: 2767
  • write with fopen clocks elapsed: 8337

为什么?

您的问题很有趣,但是高度特定于系统:

  • 在使用gcc和Glibc的Linux上,两次运行的时间非常相似
  • 在OS / X上,使用clang和Apple Libc, fopen计时似乎始终比freopen的要快。
  • 您正在Windows上运行测试,正如对getchar()的最终调用所建议的那样...很遗憾,我无法测试该系统以尝试交叉检查您的观察结果。

Microsoft可能在其运行时库中做了一些奇怪的事情,但是您更有可能对两个独立的1GB文件的创建进行基准测试。 由于文件系统的状态,其缓存或其他特定于操作系统的原因,第二个文件的创建时间可能会比第一个文件花费的时间更长。 您应该尝试通过在关闭每个文件后删除每个文件来消除这种潜在的副作用,或者尝试以其他顺序运行测试。

暂无
暂无

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

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