Class: BigO::SpaceComplexity

Inherits:
Object
  • Object
show all
Includes:
ComplexityBase
Defined in:
lib/big-o/space_complexity.rb

Overview

Measure space complexity.

Instance Attribute Summary

Attributes included from ComplexityBase

#options, #result, #result_set, #scale

Instance Method Summary collapse

Methods included from ComplexityBase

#examine_result_set, #get_scale, #initialize, #process, #run_simulation

Instance Method Details

#measure(*args) { ... } ⇒ Float

Measures the memory space that fn is using.

Parameters:

  • args (Array)

    arguments which the given block should take

Yields:

  • function which should be measured (fn)

Returns:

  • (Float)

    measurement



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/big-o/space_complexity.rb', line 11

def measure(*args, &b)
  memory_measures = []
  GC.disable

  pid = Process.fork do
    memory_measures << `ps -o rss= -p #{Process.pid}`.to_i
    b.call(*args)
    memory_measures << `ps -o rss= -p #{Process.pid}`.to_i
    exit
  end

  while (memory_indicator = `ps -o rss= -p #{pid}`.to_i)
    break if memory_indicator == 0
    memory_measures << memory_indicator
  end

  Process.wait

  GC.enable

  if memory_measures.size > 2
    memory_measures.max - memory_measures.min
  else
    0
  end
end