I started doing comparisons between:
- inserting at the front of list
- inserting at the back of a vector
- inserting at the front of a deque
But then I noticed that even on push_back()
the deque seemed to be faster. I must be doing something wrong, I can't believe a more general container would outperform a particular one.
My code using google benchmark:
#include "benchmark/benchmark.h"
#include <deque>
#include <vector>
#define NUM_INS 1000
static void BM_InsertVector(benchmark::State& state) {
std::vector<int> v;
v.reserve(NUM_INS);
while (state.KeepRunning()) {
state.PauseTiming();
v.clear();
state.ResumeTiming();
for (size_t i = 0; i < NUM_INS; i++)
v.push_back(i);
}
}
BENCHMARK(BM_InsertVector);
static void BM_InsertDeque(benchmark::State& state) {
std::deque<int> v;
while (state.KeepRunning()) {
state.PauseTiming();
v.clear();
state.ResumeTiming();
for (size_t i = 0; i < NUM_INS; i++)
v.push_back(i);
}
}
BENCHMARK(BM_InsertDeque);
BENCHMARK_MAIN();
Results:
Run on (1 X 2592 MHz CPU )
2016-02-18 14:03:47
Benchmark Time(ns) CPU(ns) Iterations
------------------------------------------------
BM_InsertVector 2820 2470 312500
BM_InsertDeque 1872 1563 406977
I notice some differences when playing with the number of elements, but deque always outperforms vector.
EDIT:
compiler: gcc version 5.2.1
compiling with: g++ -O3 -std=c++11 push_front.cpp -lbenchmark -lpthread
I think the -O3
is actually instrumental; when I turn it off I get a slightly worse deque performance.