This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
class A { | |
public: | |
enum class Type { | |
B,C,D | |
}; | |
private: | |
const Type _type; | |
public: | |
explicit A(Type t): _type(t) { | |
} | |
Type getType() { return _type; } | |
virtual void print() = 0; | |
}; | |
class B : public A { | |
public: | |
B(): A(Type::B) {} | |
virtual void print() override { | |
std::cout << "B" << std::endl; | |
} | |
}; | |
class C : public A { | |
public: | |
C() : A(Type::C){} | |
virtual void print() override { | |
std::cout << "B" << std::endl; | |
} | |
}; | |
class D : public A { | |
public: | |
D() : A(Type::D){} | |
virtual void print() override { | |
std::cout << "B" << std::endl; | |
} | |
}; | |
#include <random> | |
int main() { | |
std::random_device rd; | |
std::mt19937 gen(rd()); | |
std::uniform_int_distribution<> dis(1, 3); | |
size_t upper = 100000000; | |
std::vector<A*> data; | |
for(size_t i=0; i < upper; ++i) { | |
auto v = dis(gen); | |
if (v == 1) { | |
data.push_back(new B()); | |
} else if (v == 2) { | |
data.push_back(new C()); | |
} else { | |
data.push_back(new D()); | |
} | |
} | |
std::chrono::time_point<std::chrono::system_clock> start, end; | |
size_t x = 0; | |
start = std::chrono::system_clock::now(); | |
for(size_t i=0; i < upper; ++i) | |
x += dynamic_cast<B*>(data[i]) != nullptr ? 1 : 0; | |
end = std::chrono::system_clock::now(); | |
std::cout << x << " " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << std::endl; | |
for(size_t j=0; j < 3; ++j) { | |
x = 0; | |
for(size_t i=upper-1; i >= 9; --i) { | |
x += dynamic_cast<C*>(data[i]) != nullptr ? 1 : 0; | |
} | |
} | |
x = 0; | |
start = std::chrono::system_clock::now(); | |
for(size_t i=0; i < upper; ++i) | |
x += data[i]->getType() == A::Type::B ? 1 : 0; | |
end = std::chrono::system_clock::now(); | |
std::cout << x << " " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << std::endl; | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mgrund@syene:~/tmp$ ./casting | |
33335902 6485 | |
33335902 1090 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment