為什麼我們應該避免使用std :: endl

為什麼我們應該避免使用std :: endl:

在使用cout時,通常使用

std :: endl

列印換行符。對於具有很少I / O操作的小型程式,這種做法是可以接受的,但是,如果I / O操作的數量增加了,那麼程式的效率就會受到影響。

std :: endl

不僅會在流中新增換行符,還會在每次使用緩衝區時重新整理緩衝區。

cout << std :: endl

我們實際上正在做這樣的事情

cout <<‘\ n’<< std :: flush;

緩衝區重新整理是一項作業系統任務。每次重新整理緩衝區時,都必須向OS發出請求,並且這些請求相對緩慢。此外,我們每次向流中寫入內容時都不需要真正重新整理緩衝區,因為緩衝區滿時會自動重新整理。在極少數情況下,我們確實需要執行重新整理,我們可以使用

cout.flush()

或將

std :: flush

插入流中來顯示指定操作。

為什麼我們應該避免使用std :: endl

演示對效能的影響:

以下C ++程式演示了std :: endl的效能影響。我們一次使用std :: endl將100000個字串寫入兩個檔案,然後再次使用‘\ n’。在每種情況下,我們都會測量執行時間並列印這些時間

#include #include #include using namespace std; using namespace std::chrono; int main() { ofstream file1(“file1。txt”); ofstream file2(“file2。txt”); auto start = high_resolution_clock::now(); for ( int i = 0; i < 100000; i++) { file1 << “Hello World ” << std::endl ; } auto stop = high_resolution_clock::now(); auto duration = duration_cast(stop-start); cout << “Writing to file using endl took ” << duration。count() << “ microseconds” << std::endl; start = high_resolution_clock::now(); for ( int i = 0; i < 100000; i++) { file2 << “Hello World \n” ; } stop = high_resolution_clock::now(); duration = duration_cast(stop-start); cout << “Writing to file using \\n took ” << duration。count() << “ microseconds”<< std::endl; file1。close(); file2。close(); return 0; }

輸出:(取決於機器)

使用endl寫入檔案花費了3272微秒使用\ n寫入檔案花費了1533微秒

從輸出std :: endl可以看到,時間花費了將近一倍。在某些系統上,效能影響可能會更糟。

學習更多知識。免費領取學習資料及教程,請檢視下方圖片:

為什麼我們應該避免使用std :: endl