【发布时间】:2014-08-25 23:15:55
【问题描述】:
我一直在寻找一种方法来解决动态转换类型检查的缓慢问题。在你开始说我应该重新设计所有东西之前,让我告诉你设计是 5 年前决定的。我无法修复之后出现的所有 400,000 行代码(我希望可以),但我可以进行一些更改。我已经对类型识别进行了这个小测试:
#include <iostream>
#include <typeinfo>
#include <stdint.h>
#include <ctime>
using namespace std;
#define ADD_TYPE_ID \
static intptr_t type() { return reinterpret_cast<intptr_t>(&type); }\
virtual intptr_t getType() { return type(); }
struct Base
{
ADD_TYPE_ID;
};
template <typename T>
struct Derived : public Base
{
ADD_TYPE_ID;
};
int main()
{
Base* b = new Derived<int>();
cout << "Correct Type: " << (b->getType() == Derived<int>::type()) << endl; // true
cout << "Template Type: " << (b->getType() == Derived<float>::type()) << endl; // false
cout << "Base Type: " << (b->getType() == Base::type()) << endl; // false
clock_t begin = clock();
{
for (size_t i = 0; i < 100000000; i++)
{
if (b->getType() == Derived<int>::type())
Derived <int>* d = static_cast<Derived<int>*> (b);
}
}
clock_t end = clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "Type elapsed: " << elapsed << endl;
begin = clock();
{
for (size_t i = 0; i < 100000000; i++)
{
Derived<int>* d = dynamic_cast<Derived<int>*>(b);
if (d);
}
}
end = clock();
elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "Type elapsed: " << elapsed << endl;
begin = clock();
{
for (size_t i = 0; i < 100000000; i++)
{
Derived<int>* d = dynamic_cast<Derived<int>*>(b);
if ( typeid(d) == typeid(Derived<int>*) )
static_cast<Derived<int>*> (b);
}
}
end = clock();
elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "Type elapsed: " << elapsed << endl;
return 0;
}
似乎使用类 id(上面的第一次解决方案)将是在运行时进行类型检查的最快方法。 这会导致线程出现任何问题吗?有没有更好的方法在运行时检查类型(重构不多)?
编辑:我还需要补充一点,这需要与 TI 编译器一起使用,目前仅支持 '03
【问题讨论】:
-
在 Career Overflow 上获得一个帐户?
-
我不知道
if ( typeid(d) == typeid(Derived<int>*) )打算做什么。此外,您的任何测试似乎都没有副作用,它们都可能被优化器删除。 -
@KerrekSB 你的意思是 OP 在开始处理遗留代码之前应该辞职?
-
@πάνταῥεῖ:好吧,如果我被告知我必须快速制作 400k loc 的缓慢遗留代码,我想知道如果失败了我的选择......
-
@KerrekSB “好吧,如果我被告知我必须制作 400k loc ...” 我会尝试开发一些工具来支持重构(估计努力和成功机会分别);)...