gpt4 book ai didi

c++ - 如何在 Windows 中复制加速(苹果 DSP 库)功能?

转载 作者:可可西里 更新时间:2023-11-01 09:48:44 28 4
gpt4 key购买 nike

我将尽可能简洁:

由于某些非常具体的硬件限制,我有一个项目需要移植到 Windows。有一个小实用程序类使用 Accelerate(Apple DSP 库)执行 vector 距离计算。我需要重写它以使其在没有所述库的情况下运行,但一直无法找到合适的替代品。我的最佳行动方案是什么?

#include <Accelerate/Accelerate.h>

inline float distBetween(float *x, float *y, unsigned int count) {
float *tmp = (float*)malloc(count * sizeof(float));
// float tmp[count];
//t = y - x
vDSP_vsub(x, 1, y, 1, tmp, 1, count);
//t.squared
vDSP_vsq(tmp, 1, tmp, 1, count);
//t.sum
float sum;
vDSP_sve(tmp, 1, &sum, count);
delete tmp;
return sqrt(sum);
}

inline float cosineDistance(float *x, float *y, unsigned int count) {
float dotProd, magX, magY;
float *tmp = (float*)malloc(count * sizeof(float));

vDSP_dotpr(x, 1, y, 1, &dotProd, count);

vDSP_vsq(x, 1, tmp, 1, count);
vDSP_sve(tmp, 1, &magX, count);
magX = sqrt(magX);

vDSP_vsq(y, 1, tmp, 1, count);
vDSP_sve(tmp, 1, &magY, count);
magY = sqrt(magY);

delete tmp;

return 1.0 - (dotProd / (magX * magY));
}

最佳答案

vector 函数通常是通过特定的汇编语言指令来实现的。这个实现非常慢。也许您需要一个使用 SSE 指令的库。

在您的代码中,所有参数 stride_x、stride_y、stride_res 都等于 1,因此我建议您将它们从函数参数中删除。 Сode 应该更快。

//t = y - x    
float
vDSP_vsub(float *x, int stride_x, float *y, int stride_y, float *res, int stride_res, int count)
{
while(count > 0)
{
// may be *x - *y ?
*res = *y - *x;
res += stride_res;
x += stride_x;
y += stride_y;
count--;
}
}

//t.squared
float
vDSP_vsq(float *x, int stride_x, float *res, int stride_res, int count)
{
while(count > 0)
{
*res += (*x) * (*x);
x += stride_x;
res += stride_res;
count--;
}
}

//t.sum
float
vDSP_sve(float *x, int stride_x, float *res, int count)
{
*res = 0.0;
while(count > 0)
{
*res += *x;
x += stride_x;
count--;
}
}

float
vDSP_dotpr(float *x, int stride_x, float *y, int stride_y, float *res, int count)
{
*res = 0.0;
while(count > 0)
{
*res += (*x) * (*y);
x += stride_x;
y += stride_y;
count--;
}
}

关于c++ - 如何在 Windows 中复制加速(苹果 DSP 库)功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9320686/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com