How to Track Memory Usage and Execution Duration with SunSitemap

SunSitemap provides the memoryUsage() and showDuration() helper methods to monitor peak memory consumption in MiB and script execution time in seconds.

When generating large XML sitemaps for high-traffic websites, resource monitoring becomes critical for performance tuning. The msbatal/php-sitemap-generator library includes lightweight instrumentation that captures peak memory allocation and execution duration without external dependencies. These built-in utilities help you identify bottlenecks when processing thousands of URLs or handling complex compression workflows.

Understanding SunSitemap's Resource Monitoring Methods

The resource tracking capabilities reside in SunSitemap.php and operate through two distinct accessor methods. Both helpers leverage PHP's native instrumentation functions while maintaining a stateless design that prevents side effects during repeated calls.

memoryUsage()

Located at lines 311–313 in SunSitemap.php, the memoryUsage() method reports the maximum memory allocated to the PHP process during the entire script lifecycle.

The implementation queries memory_get_peak_usage() to retrieve the highest byte count observed since script startup. It converts this value to mebibytes by dividing by 1024 * 1024, then formats the result to two decimal places using number_format(). Because this captures peak usage rather than instantaneous consumption, you receive the worst-case memory footprint regardless of when you invoke the method.

showDuration()

Found at lines 320–324 in the same file, showDuration() calculates elapsed wall-clock time with microsecond precision. The constructor initializes the timer by storing microtime(true) in the private property $startTime (line 15 of the constructor). When called, the method captures a finish timestamp, computes the delta, and formats the result to four decimal places.

This approach yields precise timing data (e.g., 0.1234 s) and remains accurate even for sub-second executions. You can invoke showDuration() at any point after instantiation, though it typically follows the createSitemap() call to measure the full generation workflow.

Implementing Memory and Performance Tracking

The following examples demonstrate practical integration patterns for monitoring resource consumption during sitemap generation. Each snippet references the specific source implementations for clarity.

Basic Usage After Sitemap Generation

For standard workflows, invoke both helpers immediately after calling createSitemap() to capture the complete resource profile:

require_once 'SunSitemap.php';

$sitemap = new SunSitemap();

// Add URLs
$sitemap->addUrl('index.php', date('c'), 'daily', '1.0');
$sitemap->addUrl('about.php', date('c'), 'weekly', '0.8');

// Generate sitemap
$sitemap->createSitemap();

// Report resource usage
echo 'Peak memory: ' . $sitemap->memoryUsage() . ' MiB' . PHP_EOL;
echo 'Execution time: ' . $sitemap->showDuration() . ' s' . PHP_EOL;

Monitoring Large-Scale Generation with Compression

When processing extensive URL lists with GZIP compression enabled, tracking overhead becomes essential for capacity planning:

require_once 'SunSitemap.php';

// Initialize with compression enabled
$sitemap = new SunSitemap('https://example.com', 'sitemaps', 50000, true);

// Bulk URL insertion (e.g., from database)
foreach ($largeUrlDataset as $url) {
    $sitemap->addUrl($url['loc'], $url['lastmod'], $url['changefreq'], $url['priority']);
}

// Execute generation
$sitemap->createSitemap();

// Precision reporting
printf(
    "Resource consumption: %s MiB peak memory, %s seconds elapsed\n",
    $sitemap->memoryUsage(),
    $sitemap->showDuration()
);

Embedding Metrics in Development Artifacts

You can capture statistics for logging or documentation purposes before finalizing output files:

require_once 'SunSitemap.php';

$sitemap = new SunSitemap();
$sitemap->addUrl('index.php', date('c'), 'daily', '1');
$sitemap->createSitemap();

$mem  = $sitemap->memoryUsage();
$time = $sitemap->showDuration();

// Append metadata to robots.txt as comments
$metadata = "# Sitemap generation metrics\n";

$metadata .= "# Peak memory: {$mem} MiB\n";

$metadata .= "# Duration: {$time} s\n";

file_put_contents('robots.txt', $metadata, FILE_APPEND);
$sitemap->updateRobots();

Performance Considerations

Both monitoring methods introduce negligible overhead. memoryUsage() performs a single system call and arithmetic operation, while showDuration() executes two microtime() lookups and basic subtraction. The stateful storage of $startTime in the constructor consumes approximately 8 bytes of memory per instance.

For production environments handling millions of URLs, these helpers help identify whether memory constraints necessitate batch processing or whether execution times warrant asynchronous generation queues. The peak memory metric specifically reveals if PHP's memory_limit configuration requires adjustment before deployment.

Summary

  • memoryUsage() (lines 311–313): Returns peak memory in MiB using memory_get_peak_usage() with 2-decimal formatting.
  • showDuration() (lines 320–324): Returns elapsed time in seconds using constructor-initialized microtime(true) with 4-decimal precision.
  • Constructor initialization (line 15): Captures start timestamp automatically upon instantiation.
  • Stateless design: Repeated calls produce consistent results without side effects.
  • Zero dependencies: Leverages native PHP functions available in all supported versions.

Frequently Asked Questions

How accurate is the execution time measurement?

The showDuration() method utilizes microtime(true), which provides microsecond precision (1/1,000,000 of a second). By storing the high-resolution timestamp during construction and comparing it against the current time at invocation, SunSitemap delivers accurate measurements suitable for benchmarking generation speeds across different server configurations.

Can I call memoryUsage() multiple times during generation?

Yes. Since memoryUsage() queries PHP's peak memory tracker rather than a stored variable, you can invoke it at any stage—during URL addition, after createSitemap(), or following compression operations. Each call returns the maximum memory allocated up to that point in the script's lifecycle.

What units does SunSitemap use for memory reporting?

The library converts raw bytes to mebibytes (MiB) using binary division (1024 * 1024). Results format to two decimal places, providing human-readable output such as 42.50 MiB rather than raw byte counts.

Does enabling ZIP compression affect the duration calculation?

The showDuration() method measures total wall-clock time from instantiation to invocation. If you enable compression via the fourth constructor parameter (true), the duration includes both XML generation and GZIP compression phases, giving you the complete resource profile for the entire operation.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →