Class: Waveform::Log

Inherits:
Object
  • Object
show all
Defined in:
lib/waveform.rb

Overview

A simple class for logging + benchmarking, nice to have good feedback on a long batch operation.

There’s probably 10,000,000 other bechmarking classes, but writing this was easier than using Google.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io = $stdout) ⇒ Log

Returns a new instance of Log.



274
275
276
# File 'lib/waveform.rb', line 274

def initialize(io=$stdout)
  @io = io
end

Instance Attribute Details

#ioObject

Returns the value of attribute io.



272
273
274
# File 'lib/waveform.rb', line 272

def io
  @io
end

Instance Method Details

#done!(msg = "") ⇒ Object

Prints the given message to the log followed by the most recent benchmark (note that it calls .end! which will stop the benchmark)



285
286
287
# File 'lib/waveform.rb', line 285

def done!(msg="")
  out "#{msg} (#{self.end!}s)\n"
end

#end!Object

Returns the elapsed time from the most recently started benchmark clock and ends the benchmark, so that a subsequent call to .end! will return the elapsed time from the previously started benchmark clock.



303
304
305
306
307
# File 'lib/waveform.rb', line 303

def end!
  elapsed = (Time.now - @benchmarks[@current])
  @current -= 1
  elapsed
end

#out(msg) ⇒ Object

Prints the given message to the log



279
280
281
# File 'lib/waveform.rb', line 279

def out(msg)
  io.print(msg) if io
end

#start!Object

Starts a new benchmark clock and returns the index of the new clock.

If .start! is called again before .end! then the time returned will be the elapsed time from the next call to start!, and calling .end! again will return the time from this call to start! (that is, the clocks are LIFO)



295
296
297
298
# File 'lib/waveform.rb', line 295

def start!
  (@benchmarks ||= []) << Time.now
  @current = @benchmarks.size - 1
end

#time?(index) ⇒ Boolean

Returns the elapsed time from the benchmark clock w/ the given index (as returned from when .start! was called).

Returns:

  • (Boolean)


311
312
313
# File 'lib/waveform.rb', line 311

def time?(index)
  Time.now - @benchmarks[index]
end

#timed(message = nil, &block) ⇒ Object

Benchmarks the given block, printing out the given message first (if given).



317
318
319
320
321
322
# File 'lib/waveform.rb', line 317

def timed(message=nil, &block)
  start!
  out(message) if message
  yield
  done!
end