应该还是cache的问题,随便写了一个跑了一下,总时间肯定还是不初始化的最好。
#include <chrono>
#include <functional>
#include <iostream>
namespace {
constexpr int POPULATION = 10000000;
struct R3 {
R3() = default;
R3(double x, double y, double z) {
data[0] = x;
data[1] = y;
data[2] = z;
}
double data[3];
};
void report(const std::function<void()> &f1, const std::function<void()> &f2, bool run_f2_again = false) {
auto start = std::chrono::high_resolution_clock::now();
f1();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Allocation done in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start) << std::endl;
start = std::chrono::high_resolution_clock::now();
f2();
end = std::chrono::high_resolution_clock::now();
std::cout << "Assignment done in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start) << std::endl;
if (run_f2_again) {
start = std::chrono::high_resolution_clock::now();
f2();
end = std::chrono::high_resolution_clock::now();
std::cout << "Assignment again in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start) << std::endl;
}
std::cout << std::endl;
}
void func1() {
std::vector<R3> rr;
report([&rr]() { rr.reserve(POPULATION); },
[&rr]() {
for (int i = 0; i < POPULATION; ++i) {
rr[i] = {(double) i * 2, (double) i + 4, (double) i + 6};
} });
}
void func2() {
std::vector<R3> rr;
report([&rr]() { rr.assign(POPULATION, R3{0, 0, 0}); },
[&rr]() {
for (int i = 0; i < POPULATION; ++i) {
rr[i] = {(double) i * 2, (double) i + 4, (double) i + 6};
} });
}
void func3() {
std::vector<R3> rr;
report([&rr]() { rr.assign(POPULATION, R3()); },
[&rr]() {
for (int i = 0; i < POPULATION; ++i) {
rr[i] = {(double) i * 2, (double) i + 4, (double) i + 6};
} });
}
}// namespace
int main() {
func1();
func2();
func3();
return 0;
}
【 在 ziqin 的大作中提到: 】
: 但是他一开始的问题是:
: vector中初始化与否导致性能差异巨大
:
: ...................
--
FROM 222.129.53.*