윈도우,이 테스트 코드를 실행 :왜 stdout로 freopened 파일을 쓰는 것이 더 빠릅니까?
write with freopen clocks elapsed: 2767
write with fopen clocks elapsed: 8337
이유 :
#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();
}
이 결과를 생성?
코드를 오프 사이트에서 호스팅하는 대신 질문의 일부로 포함하십시오. 그것을 이해하기 위해 Stack Overflow를 떠날 필요가 없습니다. – Chris
두 가지 테스트를 바꾸고 다시 시도하십시오. –
@Chris 죄송합니다. 나는 휴대 전화로 질문을 편집했다. 알림 및 도움에 감사드립니다. – vertextao