為什麼 C 語言的輸入輸出函式比 C 的輸入輸出流要快?

時間 2021-06-02 16:44:03

1樓:nolanzz

用流輸出的話,貌似用cerr會比cout更快一些;

提醒使用std::ios::sync_with_stdio(false);這個會導致流讀寫和標準讀寫不能混用,oj上讀寫會出現問題,我本地使用clang貌似沒有問題;(cin/cout這些不能和scnaf/printf這些一起用)

2樓:Isaac Pei

這個問題我以前研究過。

首先說因為iostream和stdio的同步問題導致了iostream會變慢,可以通過ios::sync_with_stdio(false)手動關閉這個同步,可能有加速作用

以下基本上是HDU和POJ的經驗,其他OJ暫時不明根據我曾經大約100多題的測試,ios::sync_with_stdio(false)只對C++ 有用,G++基本上無用,而且很多時候如果用了ios::sync_with_stdio(false)再加上cout和printf的混用,輸出順序會有不同。

所以一般的建議是scanf最好,printf可以格式化,對acm要求按照格式輸出來說最方便。

PS:現場賽教練會議的時候有時候會說iostream的事情

3樓:

這就好比兩個函式,其中乙個為了適應外界各種差異,碼了100行,還有乙個函式只處理了一種情況,碼了5行,然後有人開始比較這兩個函式的快慢,我想說這有意義嗎?

4樓:

Languages:

C/C++

GCC 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

Compilation of Submissions

C gcc -g -O2 -std=gnu99 -static $* -lm

C++ g++ -g -O2 -std=gnu++0x -static $*

順便一提雖然我不做ICPC 但都-std=gun++0x了 stl才是現在情況下acmer的首選

參考資料

分割線順便一吐說printf是呼叫os api ,cout是標頭檔案的。。。

5樓:範利鑫

如果是用了ios::sync_with_stdio(false)的話是可以達到近似scanf的速度的。

一下該函式簡單的介紹。

速度慢的主要原因是同步標準輸入輸出。

static void sync_with_stdio();

Synchronizes the C++ streams with the standard I/O system. The first time this function is called, it resets the predefined streams (cin,cout,cerr,clog) to use astdiobufobject rather than afilebufobject. After that, you can mix I/O using these streams with I/O usingstdin,stdout, andstderr.

Expect some performance decrease because there is buffering both in the stream class and in the standard I/O file system.

After the call tosync_with_stdio, theios::stdiobit is set for all affected predefined stream objects, andcoutis set to unit buffered mode.

C語言 如何輸出回文 比如輸入1234,輸出4321 ?

char InPut char Str int MaxLen char End MaxLen 1 Str charCh char p for p Str p p 0 return p intReflect char Str int MaxLen for char p end Str p printf...

C語言輸入123輸出321這個程式怎麼寫?

intserver int data return int n n?int n 0 NoneType include void function void intmain include using namespace std void function void intmain include i...

為什麼C語言要有 int 作為 main 函式的返回值,而不是 void?

main函式的返回值會被shell捕獲,並存到乙個環境變數中。在一些main loop結構的嵌入式系統中,main的返回值沒太有意義,因為嵌入式系統的軟體不會結束 上電後一直執行 或者在一些練習性質的程式中,我們也不太關注main函式的返回值。linux系統有個設計理念 乙個程式只做一件事情,並把它...