Skip to content

Commit

Permalink
Correct histograms for zero byte allocations
Browse files Browse the repository at this point in the history
If the program performs zero byte allocations, pretend that they were
one byte allocations instead. This way they'll be counted in the lowest
histogram bucket, as they should be, but we won't attempt to call
`math.log(0)` and get a math domain error.

Signed-off-by: Matt Wozniski <[email protected]>
  • Loading branch information
godlygeek committed Mar 6, 2024
1 parent 076202b commit b2d6aa8
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 4 deletions.
6 changes: 2 additions & 4 deletions src/pytest_memray/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,10 @@ def histogram(

def cli_hist(data: Iterable[float], bins: int, *, log_scale: bool = True) -> str:
bars = " ▁▂▃▄▅▆▇█"
if log_scale:
data = [math.log(number if number else 1) for number in data]
low = min(data)
high = max(data)
if log_scale:
data = map(math.log, filter(lambda number: number != 0, data))
low = math.log(low)
high = math.log(high)
data_bins = histogram(data, low=low, high=high, bins=bins)
bar_indexes = (int(elem * (len(bars) - 1) / max(data_bins)) for elem in data_bins)
result = " ".join(bars[bar_index] for bar_index in bar_indexes)
Expand Down
1 change: 1 addition & 0 deletions tests/test_pytest_memray.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,7 @@ def test_memory_alloc_fails():
@pytest.mark.parametrize(
"size, outcome",
[
(0, ExitCode.OK),
(1, ExitCode.OK),
(1024 * 1 / 10, ExitCode.OK),
(1024 * 1, ExitCode.TESTS_FAILED),
Expand Down

0 comments on commit b2d6aa8

Please sign in to comment.