You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++文件读取性能为何低于Ruby或C#?求技术分析

C++、C#、Ruby 文件读取性能对比测试记录

作为一名C新手,我正在对比C、C#和Ruby的各项性能,以此判断是否需要镜像某一第三方库。目前我聚焦在大文件读取的性能测试上,已经更新过测试内容,使用VS 2017编译C和C#代码,C采用Release(x64)模式运行。

测试场景与结果

测试用的是一个380MB、包含700万行数据的大文件:

  1. 仅读取文件不做额外处理的耗时数据:
    • Ruby:7秒
    • C#:2.5秒
    • C++(Debug模式):500+秒(中途终止,明显异常)
    • C++(Release x64编译):7.5秒
  2. 读取文件并将行拆分为对象成员存入数组的更新测试:
    C++与Ruby的性能表现接近。

测试代码

Ruby

file = File.open "test_file.txt"
while !file.eof
  line = file.readline
end

C#

StreamReader file = new StreamReader("test_file.txt");
file.Open();
while((line = file.ReadLine()) != null){ }

C++

#include "stdafx.h"
#include "string"
#include "iostream"
#include "ctime"
#include "fstream"
int main() {
    std::ios::sync_with_stdio(false);
    std::ifstream file;
    file.open("c:/sandboxCPP/test_file.txt");
    std::string line;
    std::clock_t start;
    double duration;
    start = std::clock();
    while (std::getline(file, line)) { }
    duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
    std::cout << "\nDuration: " << duration;
    while (true) { }
    return 0;
}

补充测试:Boost库的意外高性能表现

我测试了一段基于Boost的代码,性能表现极佳,仅耗时0.03秒:

vector<string> lines;
string tempString = str.str();
boost::split(lines, tempString, boost::is_any_of("\n"));
start = clock();
cout << "\nCount: " << lines.size();
int count = lines.size();
string s;
for (int i = 0; i < count; i++) {
    s = lines[i];
}

不过我不清楚Boost内部的实现机制,后续修改代码后性能会有变化,测试时我会在循环末尾输出随机记录来验证。

内容的提问来源于stack exchange,提问作者CBusBus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:28:32