加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 在SQL Server中使用什么更好:sqrt或pow?

发布时间:2020-12-12 06:45:38 所属栏目:MsSql教程 来源:网络整理
导读:在SQL Server中使用效率更高:pow(x,1/2)还是sqrt(x)?哪一个成本更低,哪一个更快? 解决方法 数学上:SQRT只是POWER的一种特殊形式,使用1/2作为指数 但在SQL Server中,实现方式不同. POWER能够将任何浮点作为第二个参数,因此检测特殊情况并针对每种特殊情况
在SQL Server中使用效率更高:pow(x,1/2)还是sqrt(x)?哪一个成本更低,哪一个更快?

解决方法

数学上:SQRT只是POWER的一种特殊形式,使用1/2作为指数

但在SQL Server中,实现方式不同. POWER能够将任何浮点作为第二个参数,因此检测特殊情况并针对每种特殊情况进行不同的优化(p2 = 1 => identity和p2 = 0.5 => sqrt)会使POWER慢于它需要的速度.

如果需要平方根,请使用SQRT. POWER明显慢了约15%.

注意:确保你使用的是POWER not POW并且使用0.5而不是1/2(字面意思),因为1/2 = 0

比较测试(以及SQL Server 2005的时序):

declare @dummy float -- to hold the result without generating resultset
declare @t1 datetime,@t2 datetime,@t3 datetime
declare @a float
set @a = rand()*1000000
declare @i int

select @t1 = getdate()
set @i = 0
while @i < 10000000
begin
    select @dummy= sqrt(@a)
    set @i = @i + 1
end

select @t2 = getdate()

set @i = 0
while @i < 10000000
begin
    select @dummy= power(@a,0.5)
    set @i = @i + 1
end
select @t3 = getdate()

select
Time_SQRT  = datediff(ms,@t1,@t2),Time_POWER = datediff(ms,@t2,@t3)

/*
Time_SQRT   Time_POWER
----------- -----------
14540       16430
14333       17053
14073       16493
*/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读