abs()vs fabs()速度差异和晶圆厂的优势() [英] abs() vs fabs() speed difference and advantage of fabs()

查看:260
本文介绍了abs()vs fabs()速度差异和晶圆厂的优势()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对abs()和fabs()函数进行了一些简单的测试,我不明白使用fabs()的优点,如果是这样的话:

< 1)慢)

2)仅适用于浮动



3)会抛出异常一个不同的类型

  In [1]:%timeit abs(5)
10000000个循环,最好是3:86.5 ns每个循环

在[3]中:%timeit fabs(5)
10000000循环,最好是3:每个循环115 ns

In [4]: %timeit abs(-5)
10000000循环,最好3:每循环88.3 ns

在[5]中:%timeit fabs(-5)
10000000循环,最好每个循环3:114 ns

在[6]中:%timeit abs(5.0)
10000000循环,最好是3:每循环92.5 ns

In [7]:%timeit fabs(5.0)
10000000循环,最好的3:每循环93.2 ns

它在float上甚至更慢!

从我的立场来看,使用fabs()的唯一好处是让代码更具可读性,因为通过使用它,你是否有其他用途的fabs()?

解决方案

来自 Tim Peters 的电子邮件回复:



< blockquote>


为什么数学有fabs函数?它和abs内置函数
都会调用fabs()来获得浮点数。数学模块提供了C89的标准
libm(+)中的所有东西。

一些扩展),fabs()是一个std C89 libm函数。



对于为什么会比$ b快$ b其他;听起来意外; math.fabs()当然可以做得更快
(按照目前的实现(通过math_1),它可以忍受一堆
的通用试图猜测libm是否应该设置errno
浪费的样板文件(没有域或范围错误)。

看起来存在没有理由使用 fabs 。只需使用 abs 即可实现所有目的。


I ran some simple tests on abs() and fabs() functions and I don't understand what are the advantages of using fabs(), if it is:

1) slower

2) works only on floats

3) will throw an exception if used on a different type

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

it's even slower on floats!

From where I am standing the only advantage of using fabs() is to make your code more readable, because by using it, you are clearly stating your intention of working with float/double point values

Is there any other use of fabs()?

解决方案

From an email response from Tim Peters:

Why does math have an fabs function? Both it and the abs builtin function wind up calling fabs() for floats. abs() is faster to boot.

Nothing deep -- the math module supplies everything in C89's standard libm (+ a few extensions), fabs() is a std C89 libm function.

There isn't a clear (to me) reason why one would be faster than the other; sounds accidental; math.fabs() could certainly be made faster (as currently implemented (via math_1), it endures a pile of general-purpose "try to guess whether libm should have set errno" boilerplate that's wasted (there are no domain or range errors possible for fabs())).

It seems there is no advantageous reason to use fabs. Just use abs for virtually all purposes.

这篇关于abs()vs fabs()速度差异和晶圆厂的优势()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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