<?php
/**
* Measures the performance of text files.
* Logs errors to a file.
*
* @param string $filePath The path to the text file.
* @return array An associative array containing performance metrics.
*/
function measureTextFilePerformance(string $filePath): array
{
$startTime = microtime(true);
$fileSize = filesize($filePath);
if ($fileSize === false) {
error_log("Error: Could not get file size for " . $filePath);
return [
'error' => 'Failed to get file size',
'size' => 0,
'time' => 0,
];
}
$handle = fopen($filePath, 'r');
if ($handle === false) {
error_log("Error: Could not open file for reading: " . $filePath);
return [
'error' => 'Failed to open file',
'size' => 0,
'time' => 0,
];
}
$fileContent = fread($handle, $fileSize);
if ($fileContent === false) {
error_log("Error: Could not read file content from: " . $filePath);
fclose($handle);
return [
'error' => 'Failed to read file content',
'size' => 0,
'time' => 0,
];
}
fclose($handle);
$endTime = microtime(true);
$executionTime = $endTime - $startTime;
return [
'error' => '',
'size' => $fileSize,
'time' => $executionTime,
];
}
// Example Usage (for testing)
if (isset($_SERVER['argv']) && count($_SERVER['argv']) > 1) {
$filePath = $_SERVER['argv'][1];
$performance = measureTextFilePerformance($filePath);
if (empty($performance['error'])) {
echo "File: " . $filePath . "\n";
echo "Size: " . $performance['size'] . " bytes\n";
echo "Execution Time: " . number_format($performance['time'], 5) . " seconds\n";
} else {
echo "Error: " . $performance['error'] . "\n";
}
} else {
echo "Usage: php script.php <file_path>\n";
}
?>
Add your comment