Skip to content

Commit

Permalink
We only ever call MemoryMeasure with a single function as argument
Browse files Browse the repository at this point in the history
  • Loading branch information
PragTob committed Mar 24, 2018
1 parent f55137b commit 3e690d1
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 36 deletions.
15 changes: 5 additions & 10 deletions lib/benchee/memory_measure.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,24 @@ defmodule Benchee.MemoryMeasure do

@spec apply(fun) :: no_return() | tuple()
def apply(fun) do
apply(:erlang, :apply, [fun, []])
end

@spec apply(atom, atom, list) :: no_return() | tuple()
def apply(module, function, arguments) do
ref = make_ref()
Process.flag(:trap_exit, true)
start_runner(module, function, arguments, ref)
start_runner(fun, ref)

receive do
{^ref, memory_usage_info} -> memory_usage_info
:shutdown -> nil
end
end

defp start_runner(module, function, arguments, ref) do
defp start_runner(fun, ref) do
parent = self()

spawn_link(fn ->
tracer = start_tracer(self())

try do
memory_usage_info = measure_memory(module, function, arguments, tracer)
memory_usage_info = measure_memory(fun, tracer)
send(parent, {ref, memory_usage_info})
catch
kind, reason -> graceful_exit(kind, reason, tracer, parent)
Expand All @@ -40,10 +35,10 @@ defmodule Benchee.MemoryMeasure do
end)
end

defp measure_memory(module, function, arguments, tracer) do
defp measure_memory(fun, tracer) do
word_size = :erlang.system_info(:wordsize)
{:garbage_collection_info, info_before} = Process.info(self(), :garbage_collection_info)
result = Kernel.apply(module, function, arguments)
result = fun.()
{:garbage_collection_info, info_after} = Process.info(self(), :garbage_collection_info)
mem_collected = get_collected_memory(tracer)

Expand Down
26 changes: 0 additions & 26 deletions test/benchee/memory_measure_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -34,30 +34,4 @@ defmodule Benchee.MemoryMeasureTest do
assert Enum.count(Process.list()) == starting_processes
end
end

describe "apply/3" do
test "returns the result of the function and the memory used (in bytes)" do
assert {memory_used, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} =
MemoryMeasure.apply(Enum, :to_list, [1..10])

assert memory_used > 350
assert memory_used < 380
end

test "will not leak processes if the applied function raises an exception" do
starting_processes = Enum.count(Process.list())

# We're capturing the IO here so the error output doesn't clog up our
# tests. We don't want stuff in our green dots!!
# We also need to sleep for 1ms because the error output is coming from
# a separate process, so we need to wait for that to emit so we can
# capture it.
capture_io(fn ->
MemoryMeasure.apply(Enum, :to_list, ["abcdef"])
Process.sleep(1)
end)

assert Enum.count(Process.list()) == starting_processes
end
end
end

0 comments on commit 3e690d1

Please sign in to comment.