Skip to content

Commit

Permalink
Add .time
Browse files Browse the repository at this point in the history
  • Loading branch information
mblumtritt committed May 28, 2024
2 parents 2f23e08 + 04d06d2 commit cb71805
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
31 changes: 29 additions & 2 deletions lib/im-lost.rb
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,29 @@ def here(test = true)
test
end

#
# Print runtime of a given block.
#
# @param title [#to_s] optional title for output
# @yield
# @yieldreturn [Object] return result
#
def time(title = nil)
raise(ArgumentError, 'no block given') unless block_given?
@output.puts(
if title
"T #{title}:"
else
loc = Kernel.caller_locations(1, 1)[0]
"T #{loc.path}:#{loc.lineno}"
end
)
tm = now
ret = yield
@output.puts(" #{now - tm} sec.")
ret
end

#
# Trace objects.
#
Expand Down Expand Up @@ -259,7 +282,7 @@ def vars(object)
@trace[traced] = traced if traced
end

protected
private

def as_sig(prefix, info, args)
args = args.join(', ')
Expand All @@ -271,7 +294,11 @@ def as_sig(prefix, info, args)
end
end

private
if defined?(Process::CLOCK_MONOTONIC)
def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
else
def now = ::Time.now
end

def _trace(arg)
id = arg.__id__
Expand Down
9 changes: 9 additions & 0 deletions spec/lib/im-lost_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -419,4 +419,13 @@ def bar = :bar
end
end
end

context 'time a block' do
it 'prints the time used to execute a given block' do
ImLost.time { sample.add(20, 22) }

expect(output).to start_with "T #{__FILE__}:#{__LINE__ - 2}"
pp(output:)
end
end
end

0 comments on commit cb71805

Please sign in to comment.