Skip to content

Instantly share code, notes, and snippets.

@camolezi
Created July 9, 2020 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camolezi/fdffbe34f149552e8601964a7cc87e73 to your computer and use it in GitHub Desktop.
Save camolezi/fdffbe34f149552e8601964a7cc87e73 to your computer and use it in GitHub Desktop.
Benchmark stl vector vs boost::matrix
time cpu-time iterations
size = 50
boost_matrix 6793 ns 6745 ns 106316
stl_vector 5539 ns 5466 ns 98350
size = 100
boost_matrix 25596 ns 25449 ns 29281
stl_vector 29938 ns 29860 ns 25969
size = 150
boost_matrix 64504 ns 63678 ns 13597
stl_vector 56799 ns 56030 ns 12640
size = 200
boost_matrix 107957 ns 106677 ns 7588
stl_vector 104706 ns 103456 ns 5679
/*
Benchmark
//use this before runnning the tests
sudo cpupower frequency-set --governor performance
./bin
//to go back to normal after benchmarks have been run
sudo cpupower frequency-set --governor powersave
how to run
g++ -O2 benchmark.cpp -std=c++17 -isystem benchmark/include -Lbenchmark/build/src -lbenchmark -lpthread -o final
./final
*/
#include <benchmark/benchmark.h>
#include <iostream>
#include <vector>
#define BOOST_UBLAS_CHECK_ENABLE 0
#define BOOST_UBLAS_NO_STD_CERR
#include <boost/numeric/ublas/matrix.hpp>
unsigned int get_size() {
unsigned val;
std::cin >> val;
return 50 * val ;
}
using type = unsigned int;
unsigned int size = get_size();
static void boost_matrix(benchmark::State& state){
using boost::numeric::ublas::matrix;
for(auto _ : state){
matrix<type> benchMatrix(size,size);
for(unsigned int x = 0; x < size; x++){
for(unsigned int y = 0; y < size; y++){
benchmark::DoNotOptimize(benchMatrix(x,y) = 1);
}
}
benchmark::ClobberMemory();
}
}
BENCHMARK(boost_matrix);
template <typename T>
class matrix {
public:
//for a mxn matrix - row major
matrix(unsigned int m, unsigned int n) : _n{n}, _m{m} { _matrix.resize(m * n); }
const T& operator()(unsigned int i, unsigned int j) const { return _matrix.at(i * _n + j); }
T& operator()(unsigned int i, unsigned int j){
if( i >= _m || j >= _n)
throw std::out_of_range("matrix access out of bounds");
return _matrix[ i * _n + j ];
}
private:
std::vector<T> _matrix;
unsigned int _n,_m;
};
static void stl_vector(benchmark::State& state){
for(auto _ : state){
matrix<type> benchMatrix(size,size);
for(unsigned int x = 0; x < size; x++){
for(unsigned int y = 0; y < size; y++){
benchmark::DoNotOptimize(benchMatrix(x,y) = 1);
}
}
benchmark::ClobberMemory();
}
}
BENCHMARK(stl_vector);
BENCHMARK_MAIN();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment