1. <?php
  2. /**
  3. * Measures the performance of text files.
  4. * Logs errors to a file.
  5. *
  6. * @param string $filePath The path to the text file.
  7. * @return array An associative array containing performance metrics.
  8. */
  9. function measureTextFilePerformance(string $filePath): array
  10. {
  11. $startTime = microtime(true);
  12. $fileSize = filesize($filePath);
  13. if ($fileSize === false) {
  14. error_log("Error: Could not get file size for " . $filePath);
  15. return [
  16. 'error' => 'Failed to get file size',
  17. 'size' => 0,
  18. 'time' => 0,
  19. ];
  20. }
  21. $handle = fopen($filePath, 'r');
  22. if ($handle === false) {
  23. error_log("Error: Could not open file for reading: " . $filePath);
  24. return [
  25. 'error' => 'Failed to open file',
  26. 'size' => 0,
  27. 'time' => 0,
  28. ];
  29. }
  30. $fileContent = fread($handle, $fileSize);
  31. if ($fileContent === false) {
  32. error_log("Error: Could not read file content from: " . $filePath);
  33. fclose($handle);
  34. return [
  35. 'error' => 'Failed to read file content',
  36. 'size' => 0,
  37. 'time' => 0,
  38. ];
  39. }
  40. fclose($handle);
  41. $endTime = microtime(true);
  42. $executionTime = $endTime - $startTime;
  43. return [
  44. 'error' => '',
  45. 'size' => $fileSize,
  46. 'time' => $executionTime,
  47. ];
  48. }
  49. // Example Usage (for testing)
  50. if (isset($_SERVER['argv']) && count($_SERVER['argv']) > 1) {
  51. $filePath = $_SERVER['argv'][1];
  52. $performance = measureTextFilePerformance($filePath);
  53. if (empty($performance['error'])) {
  54. echo "File: " . $filePath . "\n";
  55. echo "Size: " . $performance['size'] . " bytes\n";
  56. echo "Execution Time: " . number_format($performance['time'], 5) . " seconds\n";
  57. } else {
  58. echo "Error: " . $performance['error'] . "\n";
  59. }
  60. } else {
  61. echo "Usage: php script.php <file_path>\n";
  62. }
  63. ?>

Add your comment