相关疑难解决方法(0)

C和C++样式文件IO之间的性能差异

我一直听说C++文件I/O操作比C风格I/O慢得多.但我没有找到任何实际的参考文件,因为它们实际上有多慢,所以我决定在我的机器上测试它(Ubuntu 12.04,GCC 4.6.3,ext4分区格式).

首先,我在磁盘中写了一个~900MB的文件.

C++(ofstream):163s

ofstream file("test.txt");

for(register int i = 0; i < 100000000; i++) 
    file << i << endl;
Run Code Online (Sandbox Code Playgroud)

C(fprintf):12s

FILE *fp = fopen("test.txt", "w");

for(register int i = 0; i < 100000000; i++) 
    fprintf(fp, "%d\n", i);
Run Code Online (Sandbox Code Playgroud)

我期待这样的输出,它表明在C++ C中写入文件要慢得多.然后我使用C和C++ I/O读取相同的文件.让我感到惊讶的是,从文件中读取时,性能几乎没有差异.

C++(ifstream):12s

int n;
ifstream file("test.txt");

for(register int i = 0; i < 100000000; i++) 
    file >> n;
Run Code Online (Sandbox Code Playgroud)

C(fscanf):12s

FILE *fp = fopen("test.txt", "r");

for(register int i = 0; i < …
Run Code Online (Sandbox Code Playgroud)

c c++ file-io stream

24
推荐指数
2
解决办法
8766
查看次数

标签 统计

c ×1

c++ ×1

file-io ×1

stream ×1