在 C++ 中将字符串写入文件的首选方法是什么,使用“+”或多个“<<”?
What is the preferred way to write string to file in C++, use '+' or several '<<'?
我正在考虑使用 ofstream
在 C++ 中将几行写入一个文件,并且文本由几个部分(字符串和数字)组成,所以基本上我知道有两种方法。
这是一个简单的例子:
// Way 1 (Use several '<<')
f << str1 << " " << 10 << "Text" << std::endl;
// Way 2 (Use plus to have a continuous string)
f << str1 + " " + std::to_string(10) + "Text" << std::endl;
那么就效率和其他标准而言,哪一个是首选(或者可能使用 append
而不是 +
)?
我写了一个小程序尝试了这两种方法,第一个版本,使用 <<
似乎更快。无论如何,使用 std::endl
会显着抑制性能,所以我将其更改为使用 \n
.
#include <iostream>
#include <fstream>
#include <chrono>
int main () {
unsigned int iterations = 1'000'000;
std::string str1 = "Prefix string";
std::ofstream myfile;
myfile.open("example.txt");
auto start = std::chrono::high_resolution_clock::now();
for (int i=0; i < iterations; i++) {
myfile << str1 << " " << 10 << "Text" << "\n";
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = stop - start;
std::cout << "Duration: " << duration.count() << std::endl;
std::ofstream myfile2;
myfile2.open("example2.txt");
start = std::chrono::high_resolution_clock::now();
for (int i=0; i < iterations; i++) {
myfile2 << str1 + " " + std::to_string(10) + "Text" << "\n";
}
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Duration: " << duration.count() << std::endl;
myfile.close();
return 0;
}
我机器上的输出:
Duration: 91549609
Duration: 216557352
我正在考虑使用 ofstream
在 C++ 中将几行写入一个文件,并且文本由几个部分(字符串和数字)组成,所以基本上我知道有两种方法。
这是一个简单的例子:
// Way 1 (Use several '<<')
f << str1 << " " << 10 << "Text" << std::endl;
// Way 2 (Use plus to have a continuous string)
f << str1 + " " + std::to_string(10) + "Text" << std::endl;
那么就效率和其他标准而言,哪一个是首选(或者可能使用 append
而不是 +
)?
我写了一个小程序尝试了这两种方法,第一个版本,使用 <<
似乎更快。无论如何,使用 std::endl
会显着抑制性能,所以我将其更改为使用 \n
.
#include <iostream>
#include <fstream>
#include <chrono>
int main () {
unsigned int iterations = 1'000'000;
std::string str1 = "Prefix string";
std::ofstream myfile;
myfile.open("example.txt");
auto start = std::chrono::high_resolution_clock::now();
for (int i=0; i < iterations; i++) {
myfile << str1 << " " << 10 << "Text" << "\n";
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = stop - start;
std::cout << "Duration: " << duration.count() << std::endl;
std::ofstream myfile2;
myfile2.open("example2.txt");
start = std::chrono::high_resolution_clock::now();
for (int i=0; i < iterations; i++) {
myfile2 << str1 + " " + std::to_string(10) + "Text" << "\n";
}
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Duration: " << duration.count() << std::endl;
myfile.close();
return 0;
}
我机器上的输出:
Duration: 91549609
Duration: 216557352