2017-09-19 88 views
0

在Windows上,這個測試代碼執行:爲什麼寫一個用stdout打開的文件會更快?

#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

爲什麼?

+0

請將您的代碼作爲問題的一部分,而不是將其作爲異地託管。我們不應該離開Stack Overflow來理解它。 – Chris

+3

只需交換兩個測試,然後再試一次。 –

+0

@Chris很抱歉。我在手機上編輯了這個問題。感謝您的提醒和幫助! – vertextao

回答

2

你的問題很有趣,但非常具體的系統:

  • 在Linux上使用gcc和glibc的,我變得非常相似時機與無論在OS上運行
  • /X,鏗鏘和蘋果libc庫,fopen的時間似乎一貫比freopen快一點。
  • 您正在Windows上運行您的測試,因爲getchar()的最終調用暗示......我不幸地無法測試此係統來嘗試並交叉檢查您的觀察結果。

微軟在其運行時庫中做了一些奇怪的事情是可能的,但更有可能的是你真的基準測試了2個獨立的1GB文件的創建。由於文件系統的狀態,緩存或其他操作系統特定的原因,第二個文件可能比第一個文件創建時間要長。您應該嘗試通過在關閉它後關閉每個文件來消除這種潛在的副作用,或嘗試以不同的順序運行測試。

+0

是的,你是對的。當我更改測試訂單時,結果會反轉。 *'用fopen時鐘寫過去了:2346' *'用freopen時鐘寫過去了:8088' – vertextao

相關問題