Various C users that learned C prefer to continue using the printf / scanf family of functions even while coding in C , due to its accessible interface and localization capabilities. However, performance concerns may arise when comparing it to C 's ifstream. Notably, fscanf is observed to consistently outperform ifstream.
To enhance IOStreams performance, consider the following techniques:
Increasing the buffer size reduces HDD hits and system calls, thus improving performance. Set the buffer by accessing the streambuf implementation using pubsetbuf().
char Buffer[N]; std::ifstream file("file.txt"); file.rdbuf()->pubsetbuf(Buffer, N);
Locale can impact performance due to character conversion and complex system calls. Choose the default C locale, which is optimized for minimal conversion and uniformity across machines, to avoid this overhead.
This parameter did not exhibit notable performance improvements in our testing.
Our benchmarks using a simple test program reveal varying results across different platforms and compilers. The outcome suggests that the performance of IOStreams is implementation-dependent.
Here are the findings from various benchmarks:
g 4.7.2-2ubuntu1, -O3, Ubuntu 11.10 x86_64
g 4.4.5, -O3, Ubuntu Linux 10.10 x86_64
g i686-apple-darwin10-g -4.2.1 (GCC) 4.2.1, mac mini, 4GB ram
clang 3.8.0-2ubuntu4, Kubuntu 16.04 Linux 4.8-rc3
These results emphasize the significance of implementation quality in IOStreams performance optimization.
The above is the detailed content of Is C `ifstream` Always Slower Than `fscanf`?. For more information, please follow other related articles on the PHP Chinese website!