Skip to content

Commit

Permalink
Added serializable MemoryUsage recording object
Browse files Browse the repository at this point in the history
  • Loading branch information
asgrim committed Oct 8, 2019
1 parent 6f48abd commit 32a7e90
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/Helper/MemoryUsage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace Scoutapm\Helper;

use JsonSerializable;
use function memory_get_peak_usage;
use function memory_get_usage;

final class MemoryUsage implements JsonSerializable
{
/** @var int */
private $bytesAllocated;

/** @var int */
private $bytesUsed;

/** @var int */
private $peakBytesAllocated;

/** @var int */
private $peakBytesUsed;

private function __construct()
{
$this->bytesAllocated = memory_get_usage(true);
$this->bytesUsed = memory_get_usage(false);
$this->peakBytesAllocated = memory_get_peak_usage(true);
$this->peakBytesUsed = memory_get_peak_usage(false);
}

public static function record() : self
{
return new self();
}

/**
* @return int[]|array<string, int>
*
* @psalm-return array{allocated: int, used: int, peak_allocated: int, peak_used: int}
*/
public function jsonSerialize() : array
{
return [
'allocated' => $this->bytesAllocated,
'used' => $this->bytesUsed,
'peak_allocated' => $this->peakBytesAllocated,
'peak_used' => $this->peakBytesUsed,
];
}
}
32 changes: 32 additions & 0 deletions tests/Unit/Helper/MemoryUsageTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Scoutapm\UnitTests\Helper;

use PHPUnit\Framework\TestCase;
use Scoutapm\Helper\MemoryUsage;

/** @covers \Scoutapm\Helper\MemoryUsage */
final class MemoryUsageTest extends TestCase
{
public function testMemoryUsageCanBeRecorded() : void
{
$usage = MemoryUsage::record()->jsonSerialize();

self::assertArrayHasKey('allocated', $usage);
self::assertArrayHasKey('used', $usage);
self::assertArrayHasKey('peak_allocated', $usage);
self::assertArrayHasKey('peak_used', $usage);

self::assertIsInt($usage['allocated']);
self::assertIsInt($usage['used']);
self::assertIsInt($usage['peak_allocated']);
self::assertIsInt($usage['peak_used']);

self::assertGreaterThan(0, $usage['allocated']);
self::assertGreaterThan(0, $usage['used']);
self::assertGreaterThan(0, $usage['peak_allocated']);
self::assertGreaterThan(0, $usage['peak_used']);
}
}

0 comments on commit 32a7e90

Please sign in to comment.