【发布时间】:2018-01-05 21:13:57
【问题描述】:
对 C++ 完全陌生。
我正在比较 C++、C# 和 Ruby 的各个方面,看看是否需要镜像库。目前,简单读取文件(更新后)。
在 VS 2017 中编译 C++ 和 C#。C++ 处于 release(x64) 模式(或至少编译然后运行)
这些库或多或少地读取一个文件并将行分成三行,这些行构成一个对象的成员,然后存储在一个数组成员中。
为了进行压力测试,我尝试了一个 380MB(7M 行)的大文件(更新后),现在与 C++ 和 Ruby 的性能相似,
纯粹读取文件,不做其他事情的表现如下:
Ruby: 7s
C#: 2.5s
C++: 500+s (stopped running after awhile, something's clearly wrong)
C++(release build x64): 7.5s
代码:
#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;
}
编辑:以下表现非常出色。 0.03s
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];
}
s = 关于我可能不知道提升在做什么的可能性。改变了性能。
在循环结束时使用随机记录的 cout 进行测试。
谢谢
【问题讨论】:
-
您能否发布您的实际完整源代码。您提供的 c++ 代码不应编译(它缺少右括号)。
-
看到这个(可能是重复的):stackoverflow.com/q/6820765/10077 坚持
std::ios::sync_with_stdio(false);看看它是否显着加速。 -
不管减速的原因是什么,分析非发布版本是没有意义的。您实际上是在要求编译器生成更易于调试的输出,而不是在调试模式下快速输出,那么为什么要测量它呢?
-
也请在 Release 模式下尝试并报告速度差异。
-
@CBusBus 如果我们有 full 文件会有所帮助。保存一个新文件,删除所有注释掉的代码,然后尝试编译并运行它。它应该有
#include <iostream>、int main等内容。