Help us understand the problem. What is going on with this article?

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

処理にかかった時間を得て、最低時間に満たなかったら足りない分を 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

https://github.com/YumaInaura/YumaInaura/issues/2439

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away