<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Time on 答えを知りたい</title><link>https://hack.ironsand.net/tags/time/</link><description>Recent content in Time on 答えを知りたい</description><generator>Hugo -- 0.147.9</generator><language>en-US</language><lastBuildDate>Sat, 26 Apr 2014 16:59:23 +0000</lastBuildDate><atom:link href="https://hack.ironsand.net/tags/time/index.xml" rel="self" type="application/rss+xml"/><item><title>irb上でrubyスクリプトの実行速度を測る</title><link>https://hack.ironsand.net/2014/benchmark-ruby-script-in-irb/</link><pubDate>Sat, 26 Apr 2014 16:59:23 +0000</pubDate><guid>https://hack.ironsand.net/2014/benchmark-ruby-script-in-irb/</guid><description>&lt;p>例えば &lt;code>foo.rb&lt;/code>というRubyスクリプトの実行時間をシェル上で知りたかったら&lt;code>time foo.rb&lt;/code>とすればいいわけですが、残念ながら&lt;code>irb&lt;/code>上では&lt;code>time&lt;/code>コマンドをそのまま使うことができません。&lt;/p>
&lt;h3 id="解決策">解決策&lt;/h3>
&lt;p>標準で用意されている&lt;code>Benchmark&lt;/code>ライブラリを使えばOK.&lt;/p>
&lt;pre class="lang:ruby decode:true " >irb(main)&amp;gt; require 'benchmark'
irb(main)&amp;gt; puts Benchmark.measure { "a"*1_000_000_000 }
0.350000 0.400000 0.750000 ( 0.835234)&lt;/pre>
&lt;p>こんな感じで表示されます。&lt;/p>
&lt;p>&lt;code>0.750000&lt;/code>がCPUを使った時間で&lt;code>0.835234&lt;/code>が実際にかかった時間。&lt;/p>
&lt;p>気にしないといけないのはCPUを実際に使ってたじかんなので前者のほうになります。&lt;/p>
&lt;p>ちなみに自分の環境だと裏で動画のエンコードを走らせながらVirtualBox上のOSでやってたのでCPU使用時間の50倍ぐらい実際にかかってしまってました。&lt;/p>
&lt;h3 id="参考">参考&lt;/h3>
&lt;p>[Module: Benchmark (Ruby 2.1.1)][1]&lt;/p>
&lt;p>[When benchmarking, what causes a lag between CPU time and &amp;ldquo;elapsed real time&amp;rdquo;? – Stack Overflow][2]&lt;/p></description></item></channel></rss>