vb.net 为什么平方根运算这么慢?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22332750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is square root such a slow operation?
提问by Ares
I've been warned by numerous programmers not to use the square root function, and instead to raise numbers to the half power. My question is twofold:
许多程序员警告我不要使用平方根函数,而是将数字提高到一半的幂。我的问题是双重的:
What is the perceived/real performance benefit to doing this? Why is it faster?
If it really is faster, why does the square root function even exist?
这样做的感知/实际性能优势是什么?为什么更快?
如果它真的更快,为什么平方根函数甚至存在?
回答by Dmitry Bychenko
I've performed a simple test:
我进行了一个简单的测试:
Stopwatch sw = new Stopwatch();
sw.Start();
Double s = 0.0;
// compute 1e8 times either Sqrt(x) or its emulation as Pow(x, 0.5)
for (Double d = 0; d < 1e8; d += 1)
// s += Math.Sqrt(d); // <- uncomment it to test Sqrt
s += Math.Pow(d, 0.5); // <- uncomment it to test Pow
sw.Stop();
Console.Out.Write(sw.ElapsedMilliseconds);
The (averaged) outcome at my workstation (x64) is
我的工作站 (x64) 上的(平均)结果是
Sqrt: 950 ms
Pow: 5500 ms
As you can see, more specific Sqrt(x)5.5times fasterthan its emulation Pow(x, 0.5). So it's just one more legend(at least in C#) that Sqrtis that slow one should prefer Powsubstitution
如您所见,更具体的速度比它的 emulation快Sqrt(x)5.5倍。所以这只是一个传说(至少在 C# 中)是缓慢的人应该更喜欢替换Pow(x, 0.5)SqrtPow
回答by duffymo
You would have to know something about how each function is implemented to answer the question.
您必须了解每个函数是如何实现的才能回答问题。
The square root function uses Newton's methodto iteratively calculate the square root. It converges quadratically. Nothing will speed that up.
平方根函数使用牛顿法迭代计算平方根。它二次收敛。没有什么能加快速度。
The other functions, exp() and ln(x), have implementations that have their own convergence/complexity issues. For example, it's possible to implement both as series sums. A certain number of terms are required to maintain sufficient accuracy.
其他函数 exp() 和 ln(x) 的实现都有自己的收敛/复杂性问题。例如,可以将两者都实现为series sums。需要一定数量的项才能保持足够的准确性。
All bets are off if those functions happen to be implemented in native code. Those might be faster than anything you'll write.
如果这些功能碰巧是在本机代码中实现的,那么所有的赌注都将失败。这些可能比你写的任何东西都快。
Knowing those would let you make an informed decision. I would not take it on faith because those programmers "know" the answer.
了解这些将使您做出明智的决定。我不会相信它,因为那些程序员“知道”答案。
Unless you're doing intensive numerical work, I'd say that the choice won't affect your overall program performance. It's micro-optimization that's best avoided, unless you're doing serious large-scale scientific programming.
除非你在做大量的数值工作,否则我会说这个选择不会影响你的整体程序性能。最好避免微优化,除非您正在进行严肃的大规模科学编程。

