gpt4 book ai didi

c++ - 提高ofstream的性能

转载 作者:行者123 更新时间:2023-11-30 02:57:15 26 4
gpt4 key购买 nike

我正在使用以下方法将字符串写入文本文件:

ofstream ofs("ofs.txt", ios_base::binary);
std::string str = "Hi";
for (int i = 0 ; i < 10000000 ; i++) {
ofs << str.c_str();
ofs << "\n" ;
}

但是,这需要很长时间才能执行。任何人都可以帮助我如何提高上述性能。或者任何其他更快的方式将字符串写入文件。

谢谢。

最佳答案

在某些情况下,我发现 C++ I/O 流往往比 C 慢 <stdio.h> FILE* .

我在以下测试中也得到了确认:

#define _CRT_SECURE_NO_WARNINGS // for stupid fopen_s warning
#include <stdio.h>
#include <exception>
#include <fstream>
#include <iostream>
#include <ostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <windows.h>
using namespace std;

long long Counter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return li.QuadPart;
}

long long Frequency()
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
return li.QuadPart;
}

void PrintTime(long long start, long long finish, const char * s)
{
cout << s << ": " << (finish - start) * 1000.0 / Frequency() << " ms" << endl;
}

// RAII wrapper to FILE*
class File
{
public:
explicit File(FILE * f)
: m_file(f)
{}

~File()
{
fclose(m_file);
}

FILE* Get() const
{
return m_file;
}

bool IsOpen() const
{
return (m_file != nullptr);
}

private:
FILE* m_file;

File(const File&);
File& operator=(const File&);
};

void TestIoStream(const vector<string>& lines)
{
ofstream ofs("ofs.txt", ios_base::binary);
for(auto it = lines.begin(); it != lines.end(); ++it)
{
ofs << it->c_str();
ofs << "\n" ;
}
}

void TestStdioFile(const vector<string>& lines)
{
File file( fopen("cfile.txt", "wt") );
if (! file.IsOpen())
throw runtime_error("Can't open C FILE*.");

for(auto it = lines.begin(); it != lines.end(); ++it)
{
fputs( it->c_str(), file.Get());
fputs( "\n", file.Get());
}
}

int main()
{
static const int kExitOk = 0;
static const int kExitError = 1;
try
{
cout << "Building test lines...";
vector<string> lines;
for (int i = 0; i < 10000000; i++)
lines.push_back("Hi");
cout << "done. ";
cout << "(Count = " << lines.size() << ")" << endl;

long long start = 0;
long long finish = 0;

start = Counter();
TestIoStream(lines);
finish = Counter();
PrintTime(start, finish, "C++ I/O stream");

start = Counter();
TestStdioFile(lines);
finish = Counter();
PrintTime(start, finish, "C FILE*");

return kExitOk;
}
catch(const exception& e)
{
cerr << "\n*** ERROR: " << e.what() << endl;
return kExitError;
}
}

使用 VS2010 SP1 (VC10) 编译:

cl /EHsc /W4 /nologo /MT /O2 /GL test.cpp

测试结果:

Building test lines...done. (Count = 10000000)
C++ I/O stream: 2892.39 ms
C FILE*: 2131.09 ms

关于c++ - 提高ofstream的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14771248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com