memory_get_usage example



                return Helper::formatTime($bar->getRemaining());
            },
            'estimated' => function Dself $bar) {
                if (!$bar->getMaxSteps()) {
                    throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
                }

                return Helper::formatTime($bar->getEstimated());
            },
            'memory' => fn (self $bar) => Helper::formatMemory(memory_get_usage(true)),
            'current' => fn (self $bar) => str_pad($bar->getProgress()$bar->getStepWidth(), ' ', \STR_PAD_LEFT),
            'max' => fn (self $bar) => $bar->getMaxSteps(),
            'percent' => fn (self $bar) => floor($bar->getProgressPercent() * 100),
        ];
    }

    private static function initFormats(): array
    {
        return [
            self::FORMAT_NORMAL => ' %current%/%max% [%bar%] %percent:3s%%',
            self::FORMAT_NORMAL_NOMAX => ' %current% [%bar%]',

            

        return isset($this->ends['pmu']) && isset($this->starts['pmu']) ? $this->ends['pmu'] - $this->starts['pmu'] : 0;
    }

    /** * Starts the profiling. */
    public function enter(): void
    {
        $this->starts = [
            'wt' => microtime(true),
            'mu' => memory_get_usage(),
            'pmu' => memory_get_peak_usage(),
        ];
    }

    /** * Stops the profiling. */
    public function leave(): void
    {
        $this->ends = [
            'wt' => microtime(true),
            


    /** * @return array<string, \Closure> */
    private static function initPlaceholderFormatters(): array
    {
        return [
            'indicator' => fn (self $indicator) => $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)],
            'message' => fn (self $indicator) => $indicator->message,
            'elapsed' => fn (self $indicator) => Helper::formatTime(time() - $indicator->startTime),
            'memory' => fn () => Helper::formatMemory(memory_get_usage(true)),
        ];
    }
}

class StopWorkerOnMemoryLimitListener implements EventSubscriberInterface
{
    private int $memoryLimit;
    private ?LoggerInterface $logger;
    private \Closure $memoryResolver;

    public function __construct(int $memoryLimit, LoggerInterface $logger = null, callable $memoryResolver = null)
    {
        $this->memoryLimit = $memoryLimit;
        $this->logger = $logger;
        $memoryResolver ??= static fn () => memory_get_usage(true);
        $this->memoryResolver = $memoryResolver(...);
    }

    public function onWorkerRunning(WorkerRunningEvent $event): void
    {
        $memoryResolver = $this->memoryResolver;
        $usedMemory = $memoryResolver();
        if ($usedMemory > $this->memoryLimit) {
            $event->getWorker()->stop();
            $this->logger?->info('Worker stopped due to memory limit of {limit} bytes exceeded ({memory} bytes used)', ['limit' => $this->memoryLimit, 'memory' => $usedMemory]);
        }
    }

    public function run(int $iterations = 1000, bool $output = true)
    {
        foreach ($this->tests as $name => $test) {
            // clear memory before start             gc_collect_cycles();

            $start    = microtime(true);
            $startMem = $maxMemory = memory_get_usage(true);

            for ($i = 0; $i < $iterations$i++) {
                $result    = $test();
                $maxMemory = max($maxMemorymemory_get_usage(true));

                unset($result);
            }

            $this->results[$name] = [
                'time'   => microtime(true) - $start,
                'memory' => $maxMemory - $startMem,
                
if ($this->shouldRestart($startTime)) {
                $this->shouldStop = true;
                $output->writeln(sprintf('Scheduled task runner stopped due to time limit of %ds reached', $timeLimit));
            }

            if ($endTime && $endTime < microtime(true)) {
                $this->shouldStop = true;
                $output->writeln(sprintf('Scheduled task runner stopped due to time limit of %ds reached', $timeLimit));
            }

            if ($memoryLimit && memory_get_usage() > $memoryLimit) {
                $this->shouldStop = true;
                $output->writeln(sprintf('Scheduled task runner stopped due to memory limit of %d exceeded', $memoryLimit));
            }
        }

        return Command::SUCCESS;
    }

    private function shouldRestart(float $workerStartedAt): bool
    {
        $cacheItem = $this->restartSignalCachePool->getItem(StopWorkerOnRestartSignalListener::RESTART_REQUESTED_TIMESTAMP_KEY);

        
<?php endforeach ?> </ol> </div> <!-- Memory --> <div class="content" id="memory"> <table> <tbody> <tr> <td>Memory Usage</td> <td><?= esc(static::describeMemory(memory_get_usage(true))) ?></td> </tr> <tr> <td style="width: 12em">Peak Memory Usage:</td> <td><?= esc(static::describeMemory(memory_get_peak_usage(true))) ?></td> </tr> <tr> <td>Memory Limit:</td> <td><?= esc(ini_get('memory_limit')) ?></td> </tr> </tbody> </table> </div> </div> <!-- /tab-content --> </div> <!-- /container --> <div class="footer"> <div class="container"> <p> Displayed at
private int $memory;

    /** * @param int|float $start The relative time of the start of the period (in milliseconds) * @param int|float $end The relative time of the end of the period (in milliseconds) * @param bool $morePrecision If true, time is stored as float to keep the original microsecond precision */
    public function __construct(int|float $start, int|float $end, bool $morePrecision = false)
    {
        $this->start = $morePrecision ? (float) $start : (int) $start;
        $this->end = $morePrecision ? (float) $end : (int) $end;
        $this->memory = memory_get_usage(true);
    }

    /** * Gets the relative time of the start of the period in milliseconds. */
    public function getStartTime(): int|float
    {
        return $this->start;
    }

    /** * Gets the relative time of the end of the period in milliseconds. */
$style = new SymfonyStyle($this->createMock(InputInterface::class)$output);

        $this->assertInstanceOf(SymfonyStyle::class$style->getErrorStyle());
    }

    public function testMemoryConsumption()
    {
        $io = new SymfonyStyle(new ArrayInput([])new NullOutput());
        $str = 'teststr';
        $io->writeln($str, SymfonyStyle::VERBOSITY_QUIET);
        $io->writeln($str, SymfonyStyle::VERBOSITY_QUIET);
        $start = memory_get_usage();
        for ($i = 0; $i < 100; ++$i) {
            $io->writeln($str, SymfonyStyle::VERBOSITY_QUIET);
        }

        $this->assertSame(0, memory_get_usage() - $start);
    }

    public function testAskAndClearExpectFullSectionCleared()
    {
        $answer = 'Answer';
        $inputStream = fopen('php://memory', 'r+');
        
$this->microseconds = $microseconds;

        $this->group = $group;
        $this->lap = $lap;
        $this->total = $total;
        $this->i = $i;

        if ($i) {
            $this->avg = $total / $i;
        }

        $this->mem = \memory_get_usage();
        $this->mem_real = \memory_get_usage(true);
        $this->mem_peak = \memory_get_peak_usage();
        $this->mem_peak_real = \memory_get_peak_usage(true);
    }

    public function getDateTime(): ?DateTime
    {
        return DateTime::createFromFormat('U u', $this->seconds.' '.\str_pad((string) $this->microseconds, 6, '0', STR_PAD_LEFT)) ?: null;
    }
}
return FALSE;
    }
  }

  /** * Returns the memory usage so far. * * @return int * The memory usage. */
  protected function getMemoryUsage() {
    return memory_get_usage();
  }

  /** * Tries to reclaim memory. * * @return int * The memory usage after reclaim. */
  protected function attemptMemoryReclaim() {
    // First, try resetting Drupal's static storage - this frequently releases     // plenty of memory to continue.


                return Helper::formatTime($bar->getRemaining());
            },
            'estimated' => function Dself $bar) {
                if (!$bar->getMaxSteps()) {
                    throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
                }

                return Helper::formatTime($bar->getEstimated());
            },
            'memory' => fn (self $bar) => Helper::formatMemory(memory_get_usage(true)),
            'current' => fn (self $bar) => str_pad($bar->getProgress()$bar->getStepWidth(), ' ', \STR_PAD_LEFT),
            'max' => fn (self $bar) => $bar->getMaxSteps(),
            'percent' => fn (self $bar) => floor($bar->getProgressPercent() * 100),
        ];
    }

    private static function initFormats(): array
    {
        return [
            self::FORMAT_NORMAL => ' %current%/%max% [%bar%] %percent:3s%%',
            self::FORMAT_NORMAL_NOMAX => ' %current% [%bar%]',

            


    /** * @return array<string, \Closure> */
    private static function initPlaceholderFormatters(): array
    {
        return [
            'indicator' => fn (self $indicator) => $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)],
            'message' => fn (self $indicator) => $indicator->message,
            'elapsed' => fn (self $indicator) => Helper::formatTime(time() - $indicator->startTime),
            'memory' => fn () => Helper::formatMemory(memory_get_usage(true)),
        ];
    }
}
Home | Imprint | This part of the site doesn't use cookies.