我想比较使用Python和C++从stdin读取字符串的读取行,并且看到我的C++代码运行速度比等效的Python代码慢一个数量级,这让我很震惊.由于我的C++生锈了,我还不是专家Pythonista,请告诉我,如果我做错了什么或者我是否误解了什么.
(TLDR回答:包括声明:cin.sync_with_stdio(false)
或者只是fgets
改用.
TLDR结果:一直向下滚动到我的问题的底部并查看表格.)
C++代码:
#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps …
Run Code Online (Sandbox Code Playgroud) 我测试了两种写入配置:
1)Fstream缓冲:
// Initialization
const unsigned int length = 8192;
char buffer[length];
std::ofstream stream;
stream.rdbuf()->pubsetbuf(buffer, length);
stream.open("test.dat", std::ios::binary | std::ios::trunc)
// To write I use :
stream.write(reinterpret_cast<char*>(&x), sizeof(x));
Run Code Online (Sandbox Code Playgroud)
2)手动缓冲:
// Initialization
const unsigned int length = 8192;
char buffer[length];
std::ofstream stream("test.dat", std::ios::binary | std::ios::trunc);
// Then I put manually the data in the buffer
// To write I use :
stream.write(buffer, length);
Run Code Online (Sandbox Code Playgroud)
我期待同样的结果......
但是我的手动缓冲可以将性能提高10倍来写入100MB的文件,并且与正常情况相比,fstream缓冲不会改变任何东西(不重新定义缓冲区).
有人对这种情况有解释吗?
编辑:这是新闻:刚刚在超级计算机上完成的基准测试(Linux 64位架构,持续英特尔至强8核,Lustre文件系统和...希望配置良好的编译器)
(我没有解释1kB手动缓冲器"共振"的原因......)
编辑2:在1024 B的共振(如果有人对此有所了解,我很感兴趣):
我正在研究一个简单的解析器,在进行分析时我发现瓶颈在...文件读取!我摘录了非常简单的测试来比较的性能fstreams
和FILE*
读取数据的大斑点时:
#include <stdio.h>
#include <chrono>
#include <fstream>
#include <iostream>
#include <functional>
void measure(const std::string& test, std::function<void()> function)
{
auto start_time = std::chrono::high_resolution_clock::now();
function();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start_time);
std::cout<<test<<" "<<static_cast<double>(duration.count()) * 0.000001<<" ms"<<std::endl;
}
#define BUFFER_SIZE (1024 * 1024 * 1024)
int main(int argc, const char * argv[])
{
auto buffer = new char[BUFFER_SIZE];
memset(buffer, 123, BUFFER_SIZE);
measure("FILE* write", [buffer]()
{
FILE* file = fopen("test_file_write", "wb");
fwrite(buffer, 1, BUFFER_SIZE, file);
fclose(file);
});
measure("FILE* read", [buffer]() …
Run Code Online (Sandbox Code Playgroud) 我想知道在C++中使用fstream而不是FILE有什么优缺点?
我认为一个专业人士认为FILE比fstream更有效.
根据我的说法,我运行gprof
了一个C++程序,我得到了第一行输出:16.637s
time()
% cumulative self self total
time seconds seconds calls s/call s/call name
31.07 0.32 0.32 5498021 0.00 0.00 [whatever]
Run Code Online (Sandbox Code Playgroud)
为什么31.07%
它只花了.32
几秒钟的时间列表?这是一次通话时间吗?(这不是自我/电话吗?)
这是我第一次使用gprof
,所以请善待:)
编辑:通过向下滚动,似乎gprof认为我的程序需要1.03秒.为什么会这么错呢?
c++ ×5
benchmarking ×1
buffer ×1
c++11 ×1
file ×1
file-io ×1
fstream ×1
getline ×1
gprof ×1
iostream ×1
optimization ×1
performance ×1
profiling ×1
python ×1