Exercises from Chapter 13

Even Better Profiling

(Found here.)

Modify your profile method so you can turn all profiling on and off by changing only one word.

How You Could Do It

1: def​ ​profile​(block_description, &block)
# To turn profiling on/off, set this to true/false.
profiling_on = ​false
5: if​ profiling_on
start_time = Time.​new
block.​call
duration = Time.​new​ - start_time
10:  puts ​"​​#{​block_description​}​​: ​​#{​duration​}​​ seconds"
else
block.​call
end
end

How I Would Do It

1: $OPT_PROFILING_ON = ​false
def​ ​profile​(block_description, &block)
if​ $OPT_PROFILING_ON
5:  start_time = Time.​new
block[]
duration = Time.​new​ - start_time
puts ​"​​#{​block_description​ ...

Get Learn to Program, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.