Class: TimeUp::Timer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Timer

Returns a new instance of Timer.



164
165
166
167
168
169
170
# File 'lib/time_up.rb', line 164

def initialize(name)
  validate!(name)
  @name = name
  @start_time = nil
  @total_elapsed = 0.0
  @past_timings = []
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



162
163
164
# File 'lib/time_up.rb', line 162

def name
  @name
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


257
258
259
# File 'lib/time_up.rb', line 257

def active?
  !!@start_time
end

#countObject



212
213
214
# File 'lib/time_up.rb', line 212

def count
  timings.size
end

#elapsedObject



194
195
196
197
198
199
200
# File 'lib/time_up.rb', line 194

def elapsed
  if active?
    @total_elapsed + (now - @start_time)
  else
    @total_elapsed
  end
end

#maxObject



220
221
222
# File 'lib/time_up.rb', line 220

def max
  timings.max
end

#meanObject



224
225
226
227
228
# File 'lib/time_up.rb', line 224

def mean
  times = timings
  return if times.empty?
  times.sum / times.size
end

#medianObject



230
231
232
233
234
# File 'lib/time_up.rb', line 230

def median
  times = timings.sort
  return if times.empty?
  (times[(times.size - 1) / 2] + times[times.size / 2]) / 2.0
end

#minObject



216
217
218
# File 'lib/time_up.rb', line 216

def min
  timings.min
end

#percentile(percent) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/time_up.rb', line 236

def percentile(percent)
  times = timings.sort
  return if times.empty?
  return 0 if percent <= 0
  return max if percent >= 100
  return times.first if times.size == 1
  position = (percent / 100.0) * (times.size - 1)

  partial_ratio = position - position.floor
  whole, partial = times[position.floor, 2]
  whole + (partial - whole) * partial_ratio
end

#reset(force: false) ⇒ Object



202
203
204
205
206
207
208
209
210
# File 'lib/time_up.rb', line 202

def reset(force: false)
  if force
    @start_time = nil
  elsif !@start_time.nil?
    @start_time = now
  end
  @total_elapsed = 0.0
  @past_timings = []
end

#start(&blk) ⇒ Object



172
173
174
175
176
177
178
179
180
181
# File 'lib/time_up.rb', line 172

def start(&blk)
  @start_time ||= now
  if blk
    blk.call.tap do
      stop
    end
  else
    self
  end
end

#stopObject



183
184
185
186
187
188
189
190
191
192
# File 'lib/time_up.rb', line 183

def stop
  if @start_time
    duration = now - @start_time
    @past_timings.push(duration)
    @total_elapsed += duration

    @start_time = nil
  end
  @total_elapsed
end

#timingsObject



249
250
251
252
253
254
255
# File 'lib/time_up.rb', line 249

def timings
  if active?
    @past_timings + [now - @start_time]
  else
    @past_timings
  end
end