Skip to content

Instantly share code, notes, and snippets.

@talbii
Last active October 2, 2023 21:42
Show Gist options
  • Select an option

  • Save talbii/5a5f2661ca2271d4812b24d26a6077f1 to your computer and use it in GitHub Desktop.

Select an option

Save talbii/5a5f2661ca2271d4812b24d26a6077f1 to your computer and use it in GitHub Desktop.
// compile: cpp -std=c++20 virtual.cpp -o virtual -O2
#include "bench.hpp/bench.hpp" // https://github.com/talbii/bench.hpp
#include <ratio>
#include <cstddef>
#include <iostream>
struct A {
int x{};
virtual ~A() = default;
int f(void) const { return 3;}
virtual int g(void) const { return 4;}
};
int main(void) {
auto *x = new A;
constexpr std::size_t trials = 100'000'000;
std::cout << "Normal function:"
<< bench<std::micro>(trials, [&x]() { x->f(); }) << '\n';
std::cout << "Virtual function:"
<< bench<std::micro>(trials, [&x]() { x->g(); }) << '\n';
delete x;
}
// compile: cpp -std=c++20 virtual2.cpp -o virtual2 -O2
#include "bench.hpp/bench.hpp" // https://github.com/talbii/bench.hpp
#include <vector>
#include <ratio>
#include <cstddef>
#include <iostream>
struct A {
int x{};
virtual ~A() = default;
// here we let f,g modify *this, hence forcing the compiler to not completely
// ignore the function call (as is with const methods whose
// return value is ignored)
int f(void) { return ++x;}
virtual int g(void) { return ++x;}
};
int main(void) {
constexpr std::size_t size = 100'000;
constexpr std::size_t trials = 10'000;
auto vec = std::vector<A*>(size);
for (auto &p : vec)
p = new A;
for (auto i = 0u; i < 100u; ++i) for (auto &p : vec) {
p->f();
p->g();
}
std::cout << "Normal function:"
<< bench<std::micro>(trials, [&vec]() { for(auto &p : vec) p->f(); }) << '\n';
std::cout << "Virtual function:"
<< bench<std::micro>(trials, [&vec]() { for(auto &p : vec) p->g(); }) << '\n';
for (auto &p : vec)
delete p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment