Skip to content

Instantly share code, notes, and snippets.

Created May 23, 2013 12:44
Show Gist options
  • Save anonymous/5635784 to your computer and use it in GitHub Desktop.
Save anonymous/5635784 to your computer and use it in GitHub Desktop.
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment