在 MKL 和 Armadillo 类型之间进行转换的有效方法

计算科学 线性代数 软件 英特尔-mkl
2021-12-23 06:08:25

我们在代码中大量使用 Armadillo,但有些地方我们更喜欢直接从向量数学库中使用 MKL。我们有 cx_vec 即双精度向量。但是犰狳的 exp 函数使用 std::exp 这不是很好,所以我们开始使用 MKL。将 cx_vec 转换为 MKL_Complex16 数组并返回时出现问题。该方法有效,但我不确定是否有更好的方法或推荐的方法。有没有更好的方法来使用 Armadillo 的 MKL?这是我们当前使用的代码示例。请注意开头的演员表和结尾的副本,这是我想重写的。欢迎任何建议。

void Exp_MKL(const cx_vec& VectorInput, cx_vec& VectorOutput) {
  if (VectorInput.size() != VectorOutput.size())
    VectorOutput.set_size(VectorInput.size());

  const MKL_Complex16* in = reinterpret_cast<const MKL_Complex16*>(VectorInput.memptr());
  const int size = VectorInput.n_elem;
  MKL_Complex16* out = (MKL_Complex16*) mkl_malloc(size * sizeof(MKL_Complex16), 64);

  VZEXP(&size, in, out);
  cx_vec newoutput(reinterpret_cast<cx_double*>(out), VectorInput.size(), false);
  VectorOutput = newoutput;
  mkl_free(out);
}
1个回答

请注意,犰狳cx_double(由 使用cx_vec)只是 的别名std::complex<double>,因此实际上您是在 和 之间进行std::complex<double>转换MKL_Complex16要按预期运行的唯一要求reinterpret_cast是所涉及结构的内存布局的兼容性——在这种情况下它们是兼容的。MKL 用户指南甚至有一个MKL_Complex16重新定义为的示例std::complex<double>,在这种情况下,无需手动进行强制转换,您可以直接传递 Armadillo 指针。