Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <typeinfo>
- #include <vector>
- #include <benchmark/benchmark.h>
- struct Base {
- virtual ~Base() { }
- virtual int id() const = 0;
- };
- template <class T> struct Id;
- template<> struct Id<int> { static const int value = 1; };
- template<> struct Id<float> { static const int value = 2; };
- template<> struct Id<char> { static const int value = 3; };
- template<> struct Id<unsigned long> { static const int value = 4; };
- template <class T>
- struct Derived : Base {
- virtual int id() const { return Id<T>::value; }
- };
- int test1(std::vector<Base *>& v)
- {
- int total = 0;
- for (Base *bp : v) {
- if (Derived<int>* dp = dynamic_cast<Derived<int>*>(bp)) {
- total += 5;
- } else if (Derived<float> *dp = dynamic_cast<Derived<float>*>(bp)) {
- total += 7;
- } else if (Derived<char> *dp = dynamic_cast<Derived<char>*>(bp)) {
- total += 2;
- } else if (Derived<unsigned long> *dp = dynamic_cast<Derived<unsigned long>*>(bp)) {
- total += 9;
- }
- }
- return total;
- }
- int test2(std::vector<Base *>& v)
- {
- int total = 0;
- for (Base *bp : v) {
- const std::type_info& type = typeid(*bp);
- if (type==typeid(Derived<int>)) {
- total += 5;
- } else if (type==typeid(Derived<float>)) {
- total += 7;
- } else if (type==typeid(Derived<char>)) {
- total += 2;
- } else if (type==typeid(Derived<unsigned long>)) {
- total += 9;
- }
- }
- return total;
- }
- int test3(std::vector<Base *>& v)
- {
- int total = 0;
- for (Base *bp : v) {
- int id = bp->id();
- switch (id) {
- case 1: total += 5; break;
- case 2: total += 7; break;
- case 3: total += 2; break;
- case 4: total += 9; break;
- }
- }
- return total;
- }
- Base *new_random_subclass() {
- switch (rand() % 4) {
- case 0: return new Derived<int>;
- case 1: return new Derived<float>;
- case 2: return new Derived<char>;
- default: return new Derived<unsigned long>;
- }
- }
- template<int(&f)(std::vector<Base *>&)>
- void bench(benchmark::State& state) {
- std::vector<Base *> v(1000);
- while (state.KeepRunning()) {
- state.PauseTiming();
- for (int i=0; i < 1000; ++i) {
- v[i] = new_random_subclass();
- }
- state.ResumeTiming();
- int result = f(v);
- benchmark::DoNotOptimize(result);
- }
- }
- void bench_dynamic_cast(benchmark::State& state) { bench<test1>(state); }
- void bench_typeid(benchmark::State& state) { bench<test2>(state); }
- void bench_id_method(benchmark::State& state) { bench<test3>(state); }
- BENCHMARK(bench_dynamic_cast);
- BENCHMARK(bench_typeid);
- BENCHMARK(bench_id_method);
- BENCHMARK_MAIN();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement