这是获取数字绝对值的最快方法 [英] Which is the fastest way to get the absolute value of a number

查看:121
本文介绍了这是获取数字绝对值的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法是执行返回数字绝对值的运算的最快方法?

Which is the fastest way to implement an operation that returns the absolute value of a number?

x=root(x²)

if !isPositive(x):
    x=x*(-1)

实际上,这个问题可以解释为如果有多快(以及为什么要这样)。

Actually this question can be translated as, how fast is an if (and why please).

我的大学程序设计教授总是告诉我要避免 ,因为它们非常慢,但是我总是忘了问它有多慢以及为什么。

My college programing professors always told me to avoid ifs for they are extremely slow, but I always forgot to ask how slow and why. Does anybody here know?

推荐答案

条件比普通算术运算要慢,但是比计算像

Conditionals are slower than plain arithmetic operations, but much, much faster than something as silly as calculating the square root.

我上班时的经验法则:


  • 整数或按位运算:1个周期

  • 浮点加/减/ mul:4个周期

  • 浮点div:〜30个周期

  • 浮点幂运算:〜200个周期

  • 浮点平方根:〜60个周期,具体取决于实现方式

  • 有条件的分支:平均10个周期,如果预测正确,则更好,如果预测错误,则更糟

  • Integer or bitwise op: 1 cycle
  • Floating-point add/sub/mul: 4 cycles
  • Floating-point div: ~30 cycles
  • Floating-point exponentiation: ~200 cycles
  • Floating-point sqrt: ~60 cycles depending on implementation
  • Conditional branch: avg. 10 cycles, better if well-predicted, much worse if mispredicted

这篇关于这是获取数字绝对值的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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