假设您需要实现一个非常快速的算法来解决某些问题,它可能取决于您将从某些数据源获取到内存中的一组参数。假设这些参数一旦被解析就会像常量一样(但仍然依赖于问题)。如果知道这些常量在源代码中开始并明确写入,我希望编译器内联它们,这可以提供很好的速度改进,假设这些参数经常在瓶颈附近被访问。但是,如果它们在编译后由程序从外部源解析,则通常不会内联它们,即使您使用最终变量分配对象也是如此。 我想一个技巧可能是为每组值保存一个有效对象的副本,其中每组值都在代码中明确写出。然后可以使用相关对象。但这将耗费内存,代码将呈指数级增长。 另一个想法可能是在解析参数集之后动态编译代码。
我的问题是:是否有一些设计用于优雅地处理这个问题,更具体地说是在Java / C ++中。
答案 0 :(得分:0)
在Java中,使用JDK,您可以执行以下操作:
class MainThing {
// usual constructors etc.
double thing1;
double thing2[10];
double thing3;
void ShowProps(Properties *pProp);
// other functionality
}
void MainThing::ShowProps(Properties pProp) {
// just copies the various properties of object into pProp
}
类成员的形式打印参数集。然后附加算法的代码(你在String中的某个地方)。这是有效的,因为java编译器将 int main() {
int i, num_objs;
Properties props;
MainThing *current_obj;
MainThing *main_objs;
// allocate and instantiate elements of main_objs
#pragma omp parallel shared(main_objs, num_objs)
{
#pragma omp for private(i, current_obj, props)
for (i=0; i<num_objs; i++) {
current_obj = main_objs+i;
current_obj->ShowProps(&props);
// do lots of stuff with "props"
// this loop is "embarrassingly parallel"
// no dependence from one iteration to another
}
} // end pragma omp parallel
}
变量视为不可变常量。
这是否会让您的代码更快?我对此表示怀疑。要使这种方法产生效益,它必须运行足够长的时间来补偿编译,类加载等所需的2到3秒。