PageRenderTime 37ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/Ruby/StdLib/ruby/1.9.1/benchmark.rb

http://github.com/IronLanguages/main
Ruby | 573 lines | 189 code | 57 blank | 327 comment | 7 complexity | 118d5fd3780d6a9bcf68e68e7a13c5c0 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. =begin
  2. #
  3. # benchmark.rb - a performance benchmarking library
  4. #
  5. # $Id: benchmark.rb 27197 2010-04-02 18:22:29Z kazu $
  6. #
  7. # Created by Gotoken (gotoken@notwork.org).
  8. #
  9. # Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
  10. # Gavin Sinclair (editing).
  11. #
  12. =end
  13. # == Overview
  14. #
  15. # The Benchmark module provides methods for benchmarking Ruby code, giving
  16. # detailed reports on the time taken for each task.
  17. #
  18. # The Benchmark module provides methods to measure and report the time
  19. # used to execute Ruby code.
  20. #
  21. # * Measure the time to construct the string given by the expression
  22. # <tt>"a"*1_000_000</tt>:
  23. #
  24. # require 'benchmark'
  25. #
  26. # puts Benchmark.measure { "a"*1_000_000 }
  27. #
  28. # On my machine (FreeBSD 3.2 on P5, 100MHz) this generates:
  29. #
  30. # 1.166667 0.050000 1.216667 ( 0.571355)
  31. #
  32. # This report shows the user CPU time, system CPU time, the sum of
  33. # the user and system CPU times, and the elapsed real time. The unit
  34. # of time is seconds.
  35. #
  36. # * Do some experiments sequentially using the #bm method:
  37. #
  38. # require 'benchmark'
  39. #
  40. # n = 50000
  41. # Benchmark.bm do |x|
  42. # x.report { for i in 1..n; a = "1"; end }
  43. # x.report { n.times do ; a = "1"; end }
  44. # x.report { 1.upto(n) do ; a = "1"; end }
  45. # end
  46. #
  47. # The result:
  48. #
  49. # user system total real
  50. # 1.033333 0.016667 1.016667 ( 0.492106)
  51. # 1.483333 0.000000 1.483333 ( 0.694605)
  52. # 1.516667 0.000000 1.516667 ( 0.711077)
  53. #
  54. # * Continuing the previous example, put a label in each report:
  55. #
  56. # require 'benchmark'
  57. #
  58. # n = 50000
  59. # Benchmark.bm(7) do |x|
  60. # x.report("for:") { for i in 1..n; a = "1"; end }
  61. # x.report("times:") { n.times do ; a = "1"; end }
  62. # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  63. # end
  64. #
  65. # The result:
  66. #
  67. # user system total real
  68. # for: 1.050000 0.000000 1.050000 ( 0.503462)
  69. # times: 1.533333 0.016667 1.550000 ( 0.735473)
  70. # upto: 1.500000 0.016667 1.516667 ( 0.711239)
  71. #
  72. #
  73. # * The times for some benchmarks depend on the order in which items
  74. # are run. These differences are due to the cost of memory
  75. # allocation and garbage collection. To avoid these discrepancies,
  76. # the #bmbm method is provided. For example, to compare ways to
  77. # sort an array of floats:
  78. #
  79. # require 'benchmark'
  80. #
  81. # array = (1..1000000).map { rand }
  82. #
  83. # Benchmark.bmbm do |x|
  84. # x.report("sort!") { array.dup.sort! }
  85. # x.report("sort") { array.dup.sort }
  86. # end
  87. #
  88. # The result:
  89. #
  90. # Rehearsal -----------------------------------------
  91. # sort! 11.928000 0.010000 11.938000 ( 12.756000)
  92. # sort 13.048000 0.020000 13.068000 ( 13.857000)
  93. # ------------------------------- total: 25.006000sec
  94. #
  95. # user system total real
  96. # sort! 12.959000 0.010000 12.969000 ( 13.793000)
  97. # sort 12.007000 0.000000 12.007000 ( 12.791000)
  98. #
  99. #
  100. # * Report statistics of sequential experiments with unique labels,
  101. # using the #benchmark method:
  102. #
  103. # require 'benchmark'
  104. # include Benchmark # we need the CAPTION and FMTSTR constants
  105. #
  106. # n = 50000
  107. # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
  108. # tf = x.report("for:") { for i in 1..n; a = "1"; end }
  109. # tt = x.report("times:") { n.times do ; a = "1"; end }
  110. # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  111. # [tf+tt+tu, (tf+tt+tu)/3]
  112. # end
  113. #
  114. # The result:
  115. #
  116. # user system total real
  117. # for: 1.016667 0.016667 1.033333 ( 0.485749)
  118. # times: 1.450000 0.016667 1.466667 ( 0.681367)
  119. # upto: 1.533333 0.000000 1.533333 ( 0.722166)
  120. # >total: 4.000000 0.033333 4.033333 ( 1.889282)
  121. # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
  122. module Benchmark
  123. BENCHMARK_VERSION = "2002-04-25" #:nodoc"
  124. def Benchmark::times() # :nodoc:
  125. Process::times()
  126. end
  127. # Invokes the block with a <tt>Benchmark::Report</tt> object, which
  128. # may be used to collect and report on the results of individual
  129. # benchmark tests. Reserves <i>label_width</i> leading spaces for
  130. # labels on each line. Prints _caption_ at the top of the
  131. # report, and uses _fmt_ to format each line.
  132. # If the block returns an array of
  133. # <tt>Benchmark::Tms</tt> objects, these will be used to format
  134. # additional lines of output. If _label_ parameters are
  135. # given, these are used to label these extra lines.
  136. #
  137. # _Note_: Other methods provide a simpler interface to this one, and are
  138. # suitable for nearly all benchmarking requirements. See the examples in
  139. # Benchmark, and the #bm and #bmbm methods.
  140. #
  141. # Example:
  142. #
  143. # require 'benchmark'
  144. # include Benchmark # we need the CAPTION and FMTSTR constants
  145. #
  146. # n = 50000
  147. # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
  148. # tf = x.report("for:") { for i in 1..n; a = "1"; end }
  149. # tt = x.report("times:") { n.times do ; a = "1"; end }
  150. # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  151. # [tf+tt+tu, (tf+tt+tu)/3]
  152. # end
  153. #
  154. # <i>Generates:</i>
  155. #
  156. # user system total real
  157. # for: 1.016667 0.016667 1.033333 ( 0.485749)
  158. # times: 1.450000 0.016667 1.466667 ( 0.681367)
  159. # upto: 1.533333 0.000000 1.533333 ( 0.722166)
  160. # >total: 4.000000 0.033333 4.033333 ( 1.889282)
  161. # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
  162. #
  163. def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
  164. sync = STDOUT.sync
  165. STDOUT.sync = true
  166. label_width ||= 0
  167. fmtstr ||= FMTSTR
  168. raise ArgumentError, "no block" unless iterator?
  169. print caption
  170. results = yield(Report.new(label_width, fmtstr))
  171. Array === results and results.grep(Tms).each {|t|
  172. print((labels.shift || t.label || "").ljust(label_width),
  173. t.format(fmtstr))
  174. }
  175. STDOUT.sync = sync
  176. end
  177. # A simple interface to the #benchmark method, #bm is generates sequential reports
  178. # with labels. The parameters have the same meaning as for #benchmark.
  179. #
  180. # require 'benchmark'
  181. #
  182. # n = 50000
  183. # Benchmark.bm(7) do |x|
  184. # x.report("for:") { for i in 1..n; a = "1"; end }
  185. # x.report("times:") { n.times do ; a = "1"; end }
  186. # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
  187. # end
  188. #
  189. # <i>Generates:</i>
  190. #
  191. # user system total real
  192. # for: 1.050000 0.000000 1.050000 ( 0.503462)
  193. # times: 1.533333 0.016667 1.550000 ( 0.735473)
  194. # upto: 1.500000 0.016667 1.516667 ( 0.711239)
  195. #
  196. def bm(label_width = 0, *labels, &blk) # :yield: report
  197. benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
  198. end
  199. # Sometimes benchmark results are skewed because code executed
  200. # earlier encounters different garbage collection overheads than
  201. # that run later. #bmbm attempts to minimize this effect by running
  202. # the tests twice, the first time as a rehearsal in order to get the
  203. # runtime environment stable, the second time for
  204. # real. <tt>GC.start</tt> is executed before the start of each of
  205. # the real timings; the cost of this is not included in the
  206. # timings. In reality, though, there's only so much that #bmbm can
  207. # do, and the results are not guaranteed to be isolated from garbage
  208. # collection and other effects.
  209. #
  210. # Because #bmbm takes two passes through the tests, it can
  211. # calculate the required label width.
  212. #
  213. # require 'benchmark'
  214. #
  215. # array = (1..1000000).map { rand }
  216. #
  217. # Benchmark.bmbm do |x|
  218. # x.report("sort!") { array.dup.sort! }
  219. # x.report("sort") { array.dup.sort }
  220. # end
  221. #
  222. # <i>Generates:</i>
  223. #
  224. # Rehearsal -----------------------------------------
  225. # sort! 11.928000 0.010000 11.938000 ( 12.756000)
  226. # sort 13.048000 0.020000 13.068000 ( 13.857000)
  227. # ------------------------------- total: 25.006000sec
  228. #
  229. # user system total real
  230. # sort! 12.959000 0.010000 12.969000 ( 13.793000)
  231. # sort 12.007000 0.000000 12.007000 ( 12.791000)
  232. #
  233. # #bmbm yields a Benchmark::Job object and returns an array of
  234. # Benchmark::Tms objects.
  235. #
  236. def bmbm(width = 0, &blk) # :yield: job
  237. job = Job.new(width)
  238. yield(job)
  239. width = job.width
  240. sync = STDOUT.sync
  241. STDOUT.sync = true
  242. # rehearsal
  243. print "Rehearsal "
  244. puts '-'*(width+CAPTION.length - "Rehearsal ".length)
  245. list = []
  246. job.list.each{|label,item|
  247. print(label.ljust(width))
  248. res = Benchmark::measure(&item)
  249. print res.format()
  250. list.push res
  251. }
  252. sum = Tms.new; list.each{|i| sum += i}
  253. ets = sum.format("total: %tsec")
  254. printf("%s %s\n\n",
  255. "-"*(width+CAPTION.length-ets.length-1), ets)
  256. # take
  257. print ' '*width, CAPTION
  258. list = []
  259. ary = []
  260. job.list.each{|label,item|
  261. GC::start
  262. print label.ljust(width)
  263. res = Benchmark::measure(&item)
  264. print res.format()
  265. ary.push res
  266. list.push [label, res]
  267. }
  268. STDOUT.sync = sync
  269. ary
  270. end
  271. #
  272. # Returns the time used to execute the given block as a
  273. # Benchmark::Tms object.
  274. #
  275. def measure(label = "") # :yield:
  276. t0, r0 = Benchmark.times, Time.now
  277. yield
  278. t1, r1 = Benchmark.times, Time.now
  279. Benchmark::Tms.new(t1.utime - t0.utime,
  280. t1.stime - t0.stime,
  281. t1.cutime - t0.cutime,
  282. t1.cstime - t0.cstime,
  283. r1.to_f - r0.to_f,
  284. label)
  285. end
  286. #
  287. # Returns the elapsed real time used to execute the given block.
  288. #
  289. def realtime(&blk) # :yield:
  290. r0 = Time.now
  291. yield
  292. r1 = Time.now
  293. r1.to_f - r0.to_f
  294. end
  295. #
  296. # A Job is a sequence of labelled blocks to be processed by the
  297. # Benchmark.bmbm method. It is of little direct interest to the user.
  298. #
  299. class Job # :nodoc:
  300. #
  301. # Returns an initialized Job instance.
  302. # Usually, one doesn't call this method directly, as new
  303. # Job objects are created by the #bmbm method.
  304. # _width_ is a initial value for the label offset used in formatting;
  305. # the #bmbm method passes its _width_ argument to this constructor.
  306. #
  307. def initialize(width)
  308. @width = width
  309. @list = []
  310. end
  311. #
  312. # Registers the given label and block pair in the job list.
  313. #
  314. def item(label = "", &blk) # :yield:
  315. raise ArgumentError, "no block" unless block_given?
  316. label += ' '
  317. w = label.length
  318. @width = w if @width < w
  319. @list.push [label, blk]
  320. self
  321. end
  322. alias report item
  323. # An array of 2-element arrays, consisting of label and block pairs.
  324. attr_reader :list
  325. # Length of the widest label in the #list, plus one.
  326. attr_reader :width
  327. end
  328. module_function :benchmark, :measure, :realtime, :bm, :bmbm
  329. #
  330. # This class is used by the Benchmark.benchmark and Benchmark.bm methods.
  331. # It is of little direct interest to the user.
  332. #
  333. class Report # :nodoc:
  334. #
  335. # Returns an initialized Report instance.
  336. # Usually, one doesn't call this method directly, as new
  337. # Report objects are created by the #benchmark and #bm methods.
  338. # _width_ and _fmtstr_ are the label offset and
  339. # format string used by Tms#format.
  340. #
  341. def initialize(width = 0, fmtstr = nil)
  342. @width, @fmtstr = width, fmtstr
  343. end
  344. #
  345. # Prints the _label_ and measured time for the block,
  346. # formatted by _fmt_. See Tms#format for the
  347. # formatting rules.
  348. #
  349. def item(label = "", *fmt, &blk) # :yield:
  350. print label.ljust(@width)
  351. res = Benchmark::measure(&blk)
  352. print res.format(@fmtstr, *fmt)
  353. res
  354. end
  355. alias report item
  356. end
  357. #
  358. # A data object, representing the times associated with a benchmark
  359. # measurement.
  360. #
  361. class Tms
  362. CAPTION = " user system total real\n"
  363. FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
  364. # User CPU time
  365. attr_reader :utime
  366. # System CPU time
  367. attr_reader :stime
  368. # User CPU time of children
  369. attr_reader :cutime
  370. # System CPU time of children
  371. attr_reader :cstime
  372. # Elapsed real time
  373. attr_reader :real
  374. # Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_
  375. attr_reader :total
  376. # Label
  377. attr_reader :label
  378. #
  379. # Returns an initialized Tms object which has
  380. # _u_ as the user CPU time, _s_ as the system CPU time,
  381. # _cu_ as the children's user CPU time, _cs_ as the children's
  382. # system CPU time, _real_ as the elapsed real time and _l_
  383. # as the label.
  384. #
  385. def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
  386. @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
  387. @total = @utime + @stime + @cutime + @cstime
  388. end
  389. #
  390. # Returns a new Tms object whose times are the sum of the times for this
  391. # Tms object, plus the time required to execute the code block (_blk_).
  392. #
  393. def add(&blk) # :yield:
  394. self + Benchmark::measure(&blk)
  395. end
  396. #
  397. # An in-place version of #add.
  398. #
  399. def add!(&blk)
  400. t = Benchmark::measure(&blk)
  401. @utime = utime + t.utime
  402. @stime = stime + t.stime
  403. @cutime = cutime + t.cutime
  404. @cstime = cstime + t.cstime
  405. @real = real + t.real
  406. self
  407. end
  408. #
  409. # Returns a new Tms object obtained by memberwise summation
  410. # of the individual times for this Tms object with those of the other
  411. # Tms object.
  412. # This method and #/() are useful for taking statistics.
  413. #
  414. def +(other); memberwise(:+, other) end
  415. #
  416. # Returns a new Tms object obtained by memberwise subtraction
  417. # of the individual times for the other Tms object from those of this
  418. # Tms object.
  419. #
  420. def -(other); memberwise(:-, other) end
  421. #
  422. # Returns a new Tms object obtained by memberwise multiplication
  423. # of the individual times for this Tms object by _x_.
  424. #
  425. def *(x); memberwise(:*, x) end
  426. #
  427. # Returns a new Tms object obtained by memberwise division
  428. # of the individual times for this Tms object by _x_.
  429. # This method and #+() are useful for taking statistics.
  430. #
  431. def /(x); memberwise(:/, x) end
  432. #
  433. # Returns the contents of this Tms object as
  434. # a formatted string, according to a format string
  435. # like that passed to Kernel.format. In addition, #format
  436. # accepts the following extensions:
  437. #
  438. # <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime.
  439. # <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem")
  440. # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime
  441. # <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime
  442. # <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total
  443. # <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real
  444. # <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")
  445. #
  446. # If _fmtstr_ is not given, FMTSTR is used as default value, detailing the
  447. # user, system and real elapsed time.
  448. #
  449. def format(arg0 = nil, *args)
  450. fmtstr = (arg0 || FMTSTR).dup
  451. fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
  452. fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
  453. fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
  454. fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
  455. fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
  456. fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
  457. fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
  458. arg0 ? Kernel::format(fmtstr, *args) : fmtstr
  459. end
  460. #
  461. # Same as #format.
  462. #
  463. def to_s
  464. format
  465. end
  466. #
  467. # Returns a new 6-element array, consisting of the
  468. # label, user CPU time, system CPU time, children's
  469. # user CPU time, children's system CPU time and elapsed
  470. # real time.
  471. #
  472. def to_a
  473. [@label, @utime, @stime, @cutime, @cstime, @real]
  474. end
  475. protected
  476. def memberwise(op, x)
  477. case x
  478. when Benchmark::Tms
  479. Benchmark::Tms.new(utime.__send__(op, x.utime),
  480. stime.__send__(op, x.stime),
  481. cutime.__send__(op, x.cutime),
  482. cstime.__send__(op, x.cstime),
  483. real.__send__(op, x.real)
  484. )
  485. else
  486. Benchmark::Tms.new(utime.__send__(op, x),
  487. stime.__send__(op, x),
  488. cutime.__send__(op, x),
  489. cstime.__send__(op, x),
  490. real.__send__(op, x)
  491. )
  492. end
  493. end
  494. end
  495. # The default caption string (heading above the output times).
  496. CAPTION = Benchmark::Tms::CAPTION
  497. # The default format string used to display times. See also Benchmark::Tms#format.
  498. FMTSTR = Benchmark::Tms::FMTSTR
  499. end
  500. if __FILE__ == $0
  501. include Benchmark
  502. n = ARGV[0].to_i.nonzero? || 50000
  503. puts %Q([#{n} times iterations of `a = "1"'])
  504. benchmark(" " + CAPTION, 7, FMTSTR) do |x|
  505. x.report("for:") {for i in 1..n; a = "1"; end} # Benchmark::measure
  506. x.report("times:") {n.times do ; a = "1"; end}
  507. x.report("upto:") {1.upto(n) do ; a = "1"; end}
  508. end
  509. benchmark do
  510. [
  511. measure{for i in 1..n; a = "1"; end}, # Benchmark::measure
  512. measure{n.times do ; a = "1"; end},
  513. measure{1.upto(n) do ; a = "1"; end}
  514. ]
  515. end
  516. end