计算距离的最快方式平方 [英] Fastest way to compute distance squared

查看:129
本文介绍了计算距离的最快方式平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code在很大程度上依赖于在3D空间计算两点之间的距离。
为了避免昂贵的平方根我用整个的平方距离。
但仍占用的计算时间的主要部分,我想取代我的东西简单的功能甚至更快。
我现在有:

My code relies heavily on computing distances between two points in 3D space. To avoid the expensive square root I use the squared distance throughout. But still it takes up a major fraction of the computing time and I would like to replace my simple function with something even faster. I now have:

double distance_squared(double *a, double *b)
{
  double dx = a[0] - b[0];
  double dy = a[1] - b[1];
  double dz = a[2] - b[2];

  return dx*dx + dy*dy + dz*dz;
}

我使用宏来避免函数调用也尝试过,但它并没有多大帮助。

I also tried using a macro to avoid the function call but it doesn't help much.

#define DISTANCE_SQUARED(a, b) ((a)[0]-(b)[0])*((a)[0]-(b)[0]) + ((a)[1]-(b)[1])*((a)[1]-(b)[1]) + ((a)[2]-(b)[2])*((a)[2]-(b)[2])

我想过使用SIMD指令,但无法找到一个很好的例子或指令完整列表(理想情况下一些乘+加上两个向量)。

I thought about using SIMD instructions but could not find a good example or complete list of instructions (ideally some multiply+add on two vectors).

GPU的不是,因为只有一个点的集合在每个函数调用已知的选项。

GPU's are not an option since only one set of points is known at each function call.

什么是计算的距离的平方?的最快方法

What would be the fastest way to compute the distance squared?

推荐答案

一个好的编译器将优化,大约以及你将永远管理。一个好的编译器将使用如认为,他们将是有益的SIMD指令。请确保您打开您的编译器所有这些可能的优化。不幸的是,3维向量不倾向于与SIMD单位坐好。

A good compiler will optimize that about as well as you will ever manage. A good compiler will use SIMD instructions if it deems that they are going to be beneficial. Make sure that you turn on all such possible optimizations for your compiler. Unfortunately, vectors of dimension 3 don't tend to sit well with SIMD units.

我怀疑你将简单地必须接受由编译器产生的code是大概接近pretty最优,而且没有显著的收益可以被做。

I suspect that you will simply have to accept that the code produced by the compiler is probably pretty close to optimal and that no significant gains can be made.

这篇关于计算距离的最快方式平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆