Skip to content

Instantly share code, notes, and snippets.

@cybertxt
Last active September 20, 2017 02:55
Show Gist options
  • Save cybertxt/21dd5d8577981a197e491ff3ee4dca27 to your computer and use it in GitHub Desktop.
Save cybertxt/21dd5d8577981a197e491ff3ee4dca27 to your computer and use it in GitHub Desktop.
fopen vs. freopen speed
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <assert.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
clock_t do_write(FILE* fp, char* data, size_t len) {
// 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.
clock_t clock_begin, clock_end;
clock_begin = clock();
for (int i = 0; i < 1000; ++i) {
auto n = fwrite(data, len, 1, fp);
assert(n == 1);
}
fflush(fp);
clock_end = clock();
return clock_end - clock_begin;
}
int main() {
auto data = new char[1048576]; // 1MB
auto cache = new char[512 * 1024];
// initialize the buffer
for (int i = 0; i < 1048576; ++i)
data[i] = i;
clock_t elapsed;
auto fp_reopen = freopen("data_freopen.bin", "wb", stdout);
assert(fp_reopen != nullptr);
setvbuf(fp_reopen, cache, _IOFBF, 512 * 1024);
elapsed = do_write(fp_reopen, data, 1048576);
// redirect stdout to console
#ifdef _WIN32
freopen("CONOUT$", "w", stdout);
#else
freopen("/dev/tty", "w", stdout);
#endif
printf("write with freopen clocks elapsed: %zu\n", elapsed);
#ifdef _WIN32
Sleep(10000);
#else
sleep(10)
#endif
auto fp = fopen("data_fopen.bin", "wb");
assert(fp != nullptr);
setvbuf(fp, cache, _IOFBF, 512 * 1024);
elapsed = do_write(fp, data, 1048576);
fclose(fp);
printf("write with fopen clocks elapsed: %zu\n", elapsed);
delete[] data;
delete[] cache;
getchar();
}
@cybertxt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment