use*_*878 11 c++ performance multithreading openmp exprtk
我需要编写一个程序,其中频繁地评估字符串表达式.表达式的示例如下:
"x0*a0*a0+x1*a1+x2*a2+x3*a3+x4*a4....."
Run Code Online (Sandbox Code Playgroud)
表达式可以很长,字符串可以包含多个这样的表达式.
我使用C++库exprtk编写了一些测试代码.
vector<std::string> observation_functions;
vector<std::string> string_indices;
template<typename T>
float* get_observation(float* sing_j, float* zrlist, int num_functions,int num_variables)
{
//omp_set_nested(1);
float* results = (float*)malloc(sizeof(float)*num_functions);
exprtk::symbol_table<float> symbol_table;
exprtk::expression<T> expression;
exprtk::parser<T> parser;
int i;
for( i = 0; i < num_variables; i++)
{
symbol_table.add_variable("x"+string_indices[i], sing_j[i]);
symbol_table.add_variable("a"+string_indices[i], zrlist[i]);
}
expression.register_symbol_table(symbol_table);
for(i = 0; i < num_functions; i++)
{
parser.compile(observation_functions[i],expression);
results[i] = expression.value();
}
return results;
}
int main()
{
for( int i = 0; i < 52; i++)
{
ostringstream s2;
s2<<i;
string_indices.push_back(s2.str());
}
string hfun ="x0*a0*a0+x1*a1+x2*a2+x3*a3+x4*a4+x5*a5+x6*a6+x7*a7+x8*a8+x9*a9+x10*a10+x11*a11+x12*a12+x13*a13+x14*a14+x15*a15+x16*a16+x17*a17+x18*a18+x19*a19+x20*a20+x21*a21+x22*a22+x23*a23+x24*a24+x25*a25+x26*a26+x27*a27+x28*a28+x29*a29+x30*a30+x31*a31+x32*a32+x33*a33+x34*a34+x35*a35+x36*a36+x37*a37+x38*a38+x39*a39+x40*a40+x41*a41+x42*a42+x43*a43+x44*a44+x45*a45+x46*a46+x47*a47+x48*a48+x49*a49+x50*a50+x51*a51 ";
boost::split(observation_functions, hfun, boost::is_any_of(" "));
float *a=(float*)malloc(52*sizeof(float));
float* c=(float*)malloc(52*sizeof(float));
struct timeval t0,t1;
gettimeofday(&t0, 0);
for(int j=0; j < 210; j++)
#pragma omp parallel for schedule(static,1) num_threads(8)
for(int i=0;i<104;i++)
float* b =get_observation<float>(a,c,1,52);
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
cout<<"elapsed:"<<elapsed<<endl;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这是测试代码.实际上,每个线程将使用不同的值集来评估表达式.这段代码工作正常,但我需要让它更快.
基于其他一些实验,我发现我不能与多个线程共享一个符号表来更快地计算单个表达式.在多个线程之间共享符号表会导致内存损坏错误.
有人可以提供一些关于如何提高性能的建议.
Joh*_*est 13
假设你有N线程.比,创建N组exprtk-相关对象(包括symbol_table,expression,parser在)主节目(外的功能,和外for循环).
您可以使用它vector<>来存储它们:例如,expression它可以存储它们vector<expression> expressions;
然后,在调用函数时传递对这些对象的引用,
for(int i=0;i<104;i++)
get_observation<float>(expressions[i], more params here..)
Run Code Online (Sandbox Code Playgroud)
模板功能定义:
template <typename T> T* get_observation(expression & exp, more params here..)
你可以创建一组对象,并通过复制制作其他对象,正如Aloalo 建议的那样.
PS首选使用智能指针,/sf/answers/1332984411/ 不要忘记删除本地某处分配的内存.
| 归档时间: |
|
| 查看次数: |
1065 次 |
| 最近记录: |