In Ruby, how can I do:
在Ruby中,我该怎么做:
number_total = records / per_page
where per_page = 100
, and records = 1050
, and then round up so there are no decimals? So, instead of 10.5 it equals 11?
其中per_page = 100,记录= 1050,然后向上舍入,所以没有小数?那么,而不是10.5,它等于11?
3 个解决方案
#1
24
Edited following a comment
编辑后发表评论
number_total = (records / per_page.to_f).ceil
#2
1
@lulala Another root of all evil: cherry-picking results.
@lulala另一个邪恶的根源:挑选樱桃的结果。
Run your benchmark multiple times. I get the following:
多次运行您的基准测试。我得到以下内容:
user system total real
0.120000 0.000000 0.120000 ( 0.119281)
0.120000 0.000000 0.120000 ( 0.123431)
Which is a tie.
这是一个平局。
user system total real
0.110000 0.000000 0.110000 ( 0.118602)
0.130000 0.000000 0.130000 ( 0.127195)
Which suggests that float_op
is faster.
这表明float_op更快。
user system total real
0.150000 0.000000 0.150000 ( 0.151104)
0.120000 0.000000 0.120000 ( 0.123836)
Which suggests that integer_op
us faster.
这表明integer_op更快。
#3
0
Here comes root of all evil: a prematurely optimized method:
这是所有邪恶的根源:过早优化的方法:
class Integer
# returns quotient's ceiling integer
def div_ceil(divisor)
q = self / divisor
if self % divisor > 0
return q + 1
else
return q
end
end
end
The following benchmark code:
以下基准代码:
require 'benchmark'
$a = 1050
$b = 100
def float_op
( $a / $b.to_f ).ceil
end
def integer_op
q = $a / $b
if $a % $b > 0
return q + 1
else
return q
end
end
n = 1000000
Benchmark.bm do |x|
x.report { n.times do; float_op; end }
x.report { n.times do; integer_op; end }
end
Gives me this result
给我这个结果
user system total real
0.160000 0.000000 0.160000 ( 0.157589)
0.130000 0.000000 0.130000 ( 0.133821)
#1
24
Edited following a comment
编辑后发表评论
number_total = (records / per_page.to_f).ceil
#2
1
@lulala Another root of all evil: cherry-picking results.
@lulala另一个邪恶的根源:挑选樱桃的结果。
Run your benchmark multiple times. I get the following:
多次运行您的基准测试。我得到以下内容:
user system total real
0.120000 0.000000 0.120000 ( 0.119281)
0.120000 0.000000 0.120000 ( 0.123431)
Which is a tie.
这是一个平局。
user system total real
0.110000 0.000000 0.110000 ( 0.118602)
0.130000 0.000000 0.130000 ( 0.127195)
Which suggests that float_op
is faster.
这表明float_op更快。
user system total real
0.150000 0.000000 0.150000 ( 0.151104)
0.120000 0.000000 0.120000 ( 0.123836)
Which suggests that integer_op
us faster.
这表明integer_op更快。
#3
0
Here comes root of all evil: a prematurely optimized method:
这是所有邪恶的根源:过早优化的方法:
class Integer
# returns quotient's ceiling integer
def div_ceil(divisor)
q = self / divisor
if self % divisor > 0
return q + 1
else
return q
end
end
end
The following benchmark code:
以下基准代码:
require 'benchmark'
$a = 1050
$b = 100
def float_op
( $a / $b.to_f ).ceil
end
def integer_op
q = $a / $b
if $a % $b > 0
return q + 1
else
return q
end
end
n = 1000000
Benchmark.bm do |x|
x.report { n.times do; float_op; end }
x.report { n.times do; integer_op; end }
end
Gives me this result
给我这个结果
user system total real
0.160000 0.000000 0.160000 ( 0.157589)
0.130000 0.000000 0.130000 ( 0.133821)