Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unified way to expand records in profile #7

Merged
merged 1 commit into from
Oct 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 41 additions & 13 deletions src/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
final class Profile implements ProcessableProfileInterface, ProfileWithOutputInterface
{
private const MICROTIME_FORMAT = '%.6f';
private const SORTED_BY_TIME = true;

private ProfileState $state;
private OptionalFloat $timeBefore;
Expand Down Expand Up @@ -126,21 +127,48 @@ public function getMemoryUsageChange(): int
return $this->memoryUsageAfter->orElseThrow() - $this->memoryUsageBefore->orElseThrow();
}

public function getMemoryUsages(): array
public function getMemoryUsages(bool $sortedByTime = self::SORTED_BY_TIME): array
{
$memoryUsages = [
sprintf(self::MICROTIME_FORMAT, $this->timeBefore->orElseThrow()) => $this->memoryUsageBefore->orElseThrow(),
sprintf(self::MICROTIME_FORMAT, $this->timeAfter->orElseThrow()) => $this->memoryUsageAfter->orElseThrow(),
];
foreach ($this->children as $child) {
$memoryUsages = array_merge(
$memoryUsages,
$child->getMemoryUsages(),
);
}
return self::expandRecords(
[
sprintf(self::MICROTIME_FORMAT, $this->timeBefore->orElseThrow()) => $this->memoryUsageBefore->orElseThrow(),
sprintf(self::MICROTIME_FORMAT, $this->timeAfter->orElseThrow()) => $this->memoryUsageAfter->orElseThrow(),
],
$this->children,
__FUNCTION__,
[false],
sortedByKey: $sortedByTime,
);
}

ksort($memoryUsages);
/**
* @template TRecord of mixed
*
* @param array<numeric-string, TRecord> $myRecords
* @param array<ProfileInterface> $myChildren
* @param array<mixed> $args
*
* @return array<numeric-string, TRecord>
*/
private static function expandRecords(
array $myRecords,
array $myChildren,
string $__function__,
array $args,
bool $sortedByKey = false,
): array {
$expandedRecords = array_merge(
$myRecords,
...array_map(
static fn (ProfileInterface $child): array => call_user_func_array([$child, $__function__], $args), // @phpstan-ignore argument.type, return.type
$myChildren,
)
);

if ($sortedByKey) {
ksort($expandedRecords);
}

return $memoryUsages;
return $expandedRecords;
}
}
Loading