我试图比较逐行读取文件的性能。第一种情况是getline for string和istream,第二种情况是getline for char *和FILE *。我想知道:使用istream和FILE运行getline的性能差异*
- 为什么第一种情况太慢了?
- 是否有可能使C++代码段更快?
考虑输出下面(ifstream的第一):
Lines count: 10628126
ifstream getline: 43.2684
Lines count: 10628126
fopen getline: 1.06217
FILE *第一:
Lines count: 10628126
fopen getline: 1.96065
Lines count: 10628126
ifstream getline: 43.0428
我用于测试的代码:
#include <fstream>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <stdio.h>
using namespace std;
double gettime()
{
double result = 0;
struct timeval tv = {0};
struct timezone tz = {0};
gettimeofday(&tv, &tz);
result = tv.tv_sec + (1.0 * tv.tv_usec/1000000);
return result;
}
void read_cpp(const char * filename)
{
ifstream ifile(filename);
string line;
unsigned int i = 0;
while(getline(ifile, line)) i++;
cout << "Lines count: " << i << endl;
}
void read_c(const char * filename)
{
FILE * ifile = fopen(filename, "r");
size_t linesz = 4096+1;
char * line = new char[linesz];
unsigned int i = 0;
while(getline(&line, &linesz, ifile) > 0) i++;
delete[] line;
cout << "Lines count: " << i << endl;
fclose(ifile);
}
int main(int argc, char * argv[])
{
double tmstart;
tmstart = gettime();
read_cpp(argv[1]);
cout << "ifstream getline: " << (gettime() - tmstart) << endl;
tmstart = gettime();
read_c(argv[1]);
cout << "fopen getline: " << (gettime() - tmstart) << endl;
}
P.S.我试图交换read_cpp和read_c几乎没有区别。
UPDATE
它看起来像@Galik和@geza无法使用G ++编译器来重现问题,所以我查了Linux环境下的代码,有Ç和℃之间几乎没有差别++实现。所以这似乎是一个环境问题。本来我测量使用的是Mac OS X和默认的C++编译器,是clang
(惊讶我)时间:
$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
但所有这些事情从来没有真正g++
发生了:
$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.9/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ...
Thread model: posix
gcc version 4.9.2 (Debian 4.9.2-10)
对不起球员为不便。
UPDATE2
我已经找到了相关主题clang++ fstreams 10X slower than g++。作者还面临着由clang编译的代码的性能下降。要解决此问题,可以使用不同的stdlib
实现(-stdlib=stdlibc++
)而不是默认设置(-stdlib=libc++
)。在这种情况下clang
将显示弃用警告:
clang: warning: libstdc++ is deprecated; move to libc++ [-Wdeprecated]
但性能会好很多(即使没有优化):
Lines count: 10628126
fopen getline: 1.02899
Lines count: 10628126
ifstream getline: 1.67594
你尝试调用'read_c()''之前read_cpp()'? –
C++流可能会更慢,因为窗帘后面会发生更多事情,C++ streambuf可能会更快。但是,缓存也可能在这里工作。它可能会支付交换两种阅读方法,并看看是否有显着影响表现(麦克纳基斯击败此)。 –
@MikeNakis,是的,但它实际上没有帮助。 read_c变慢了〜1sec,而read_cpp变快了〜0.2sec。 – frist