Reputation: 776
I have a very simple code, I noticed that if I add values to QVector
constants, then I spend a lot of time than if I add sequential knowledge
code example:
QVector<int> intVector;
QTime myTimer;
myTimer.start();
for (int i = 0; i < 8500000; ++i) {
intVector.push_back(i);
}
qDebug()<< myTimer.elapsed(); // output: ~297 ms
but if i add a constant value i get this
code example:
QVector<int> intVector;
QTime myTimer;
myTimer.start();
for (int i = 0; i < 8500000; ++i) {
intVector.push_back(1);
}
qDebug()<< myTimer.elapsed(); // output: ~344 ms
tested on Qt_5_15_0_MSVC2019_32bit
.
What explains this?
Upvotes: 1
Views: 58
Reputation: 30840
Don't use QTimer to do microbenchmarks, use the google-benchmark library instead.
On my system (M1 mac) both loops are equal to within 0,04%:
------------------------------------------------------
Benchmark Time CPU Iterations
------------------------------------------------------
BM_constant 1211287 ns 1211286 ns 510
BM_i 1211735 ns 1211229 ns 573
Code:
#include <benchmark/benchmark.h>
#include <QtCore/QVector>
static void BM_constant(benchmark::State& state) {
for (auto _ : state) {
QVector<int> intVector;
for (int i = 0; i < 1000000; ++i) {
intVector.push_back(1);
}
}
}
BENCHMARK(BM_constant);
static void BM_i(benchmark::State& state) {
for (auto _ : state) {
QVector<int> intVector;
for (int i = 0; i < 1000000; ++i) {
intVector.push_back(i);
}
}
}
BENCHMARK(BM_i);
BENCHMARK_MAIN();
Upvotes: 1