小编fri*_*ist的帖子

getline 与 istream 和 FILE* 操作的性能差异

我正在尝试比较逐行读取文件的性能。第一种情况是针对 string 和 istream 的 getline,第二种情况是针对 char* 和 FILE* 的 getline。我在想:

  1. 为什么第一个案例这么慢
  2. 是否有可能使 C++ 片段更快

考虑下面的输出(首先是 ifstream):

Lines count: 10628126
ifstream getline: 43.2684
Lines count: 10628126
fopen getline: 1.06217
Run Code Online (Sandbox Code Playgroud)

首先是文件*:

Lines count: 10628126
fopen getline: 1.96065
Lines count: 10628126
ifstream getline: 43.0428
Run Code Online (Sandbox Code Playgroud)

我用于测试的代码:

#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 …
Run Code Online (Sandbox Code Playgroud)

c++ getline ifstream

5
推荐指数
1
解决办法
8179
查看次数

标签 统计

c++ ×1

getline ×1

ifstream ×1