0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#Ruby で 処理速度を平均化したい。sleep で必ず一定時間以上かかる処理を作る。

Last updated at Posted at 2019-09-15

処理にかかった時間を得て、最低時間に満たなかったら足りない分を sleep させる

def some_action
  # some action
end

start_time = Time.now.to_f

some_action

done_time = Time.now.to_f

under_time = 0.1

diff_time = under_time - (done_time - start_time)

sleep diff_time if diff_time.positive? }

ベンチマークの例

require 'benchmark'

[*1..10].map { Benchmark.realtime { start_time = Time.now.to_f; sleep rand(0.01..0.10); done_time = Time.now.to_f; under_time = 0.1; diff_time = under_time - (done_time - start_time); sleep diff_time if diff_time.positive?; } }

# => [0.10333599988371134,
 0.10502699995413423,
 0.10417600022628903,
 0.10169599996879697,
 0.1034500002861023,
 0.10172299994155765,
 0.10186100006103516,
 0.10312700038775802,
 0.10354600008577108,
 0.10065300017595291]

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?