识别Eigen中的临时对象创建

时间:2018-10-21 18:23:31

标签: c++11 eigen3

正如Eigen C ++库中的文档指出的那样,要在计算时间方面获得最大性能,我们需要尽可能避免使用临时对象。在我的应用程序中,我处理动态尺寸矩阵。我想知道在计算中如何创建临时矩阵。有什么通用方法可以识别临时矩阵的创建吗?

例如

Eigen::MatrixXf B, C, D;
....some initialization for B, C, D
Eigen::MatrixXf A = B*C+D;

在实现此操作时如何检查创建了多少个临时矩阵?

1 个答案:

答案 0 :(得分:2)

您可以为此使用插件机制。在包含任何本征标题之前,请定义以下内容:

static long int nb_temporaries;
static long int nb_temporaries_on_assert = -1;
inline void on_temporary_creation(long int size) {
  // here's a great place to set a breakpoint when debugging failures in this test!
  if(size!=0) nb_temporaries++;
  if(nb_temporaries_on_assert>0) assert(nb_temporaries<nb_temporaries_on_assert);
}

#define EIGEN_DENSE_STORAGE_CTOR_PLUGIN { on_temporary_creation(size); }

此机制在测试套件中的多个位置使用,最明显的是在product_notemporary.cpp中使用。

如果您最关心临时内存分配,则还可以通过使用-DEIGEN_RUNTIME_NO_MALLOC进行编译并使用Eigen::internal::set_is_malloc_allowed(bool);允许/禁止动态分配来进行检查

相关问题