#include <iostream>
#include <ctime>
#include <vector>
using namespace std;
struct A {
virtual void foo() {}
};
struct B : public A {
virtual void foo() override {}
};
struct C : public B {
virtual void foo() override {}
};
int main()
{
vector<A *> vec;
for (int i = 0; i < 10000000; ++i)
if (i % 2)
vec.push_back(new C());
else
vec.push_back(new B());
clock_t begin = clock();
for (auto iter : vec)
{
if (C* cptr = dynamic_cast<C*>(iter))
{
cptr->foo();
}
if (B* bptr = dynamic_cast<B*>(iter))
{
bptr->foo();
}
}
clock_t end = clock();
cout << (static_cast<double>(end) - begin) / CLOCKS_PER_SEC << endl;
begin = clock();
for (auto iter : vec)
iter->foo();
end = clock();
cout << (static_cast<double>(end) - begin) / CLOCKS_PER_SEC << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3RpbWU+CiNpbmNsdWRlIDx2ZWN0b3I+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKc3RydWN0IEEgewogICAgdmlydHVhbCB2b2lkIGZvbygpIHt9Cn07CgpzdHJ1Y3QgQiA6IHB1YmxpYyBBIHsKICAgIHZpcnR1YWwgdm9pZCBmb28oKSBvdmVycmlkZSB7fQp9OwoKc3RydWN0IEMgOiBwdWJsaWMgQiB7CiAgICB2aXJ0dWFsIHZvaWQgZm9vKCkgb3ZlcnJpZGUge30KfTsKCmludCBtYWluKCkKewogICAgdmVjdG9yPEEgKj4gdmVjOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCAxMDAwMDAwMDsgKytpKQogICAgICAgIGlmIChpICUgMikKICAgICAgICAgICAgdmVjLnB1c2hfYmFjayhuZXcgQygpKTsKICAgICAgICBlbHNlCiAgICAgICAgICAgIHZlYy5wdXNoX2JhY2sobmV3IEIoKSk7CgogICAgY2xvY2tfdCBiZWdpbiA9IGNsb2NrKCk7CiAgICBmb3IgKGF1dG8gaXRlciA6IHZlYykKICAgIHsKICAgICAgICBpZiAoQyogY3B0ciA9IGR5bmFtaWNfY2FzdDxDKj4oa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