1. import time
  2. import os
  3. def measure_filepath_performance(filepath, num_iterations=1000):
  4. """
  5. Measures the performance of accessing a file path.
  6. Args:
  7. filepath (str): The file path to measure.
  8. num_iterations (int): The number of times to access the path.
  9. Returns:
  10. float: The average time in seconds to access the file path.
  11. Returns None if the file doesn't exist.
  12. """
  13. start_time = time.time()
  14. try:
  15. for _ in range(num_iterations):
  16. os.path.exists(filepath) # Check if the path exists
  17. except FileNotFoundError:
  18. print(f"Error: File not found: {filepath}")
  19. return None
  20. end_time = time.time()
  21. elapsed_time = end_time - start_time
  22. average_time = elapsed_time / num_iterations
  23. return average_time
  24. if __name__ == '__main__':
  25. # Example usage
  26. filepath1 = "." # Current directory
  27. filepath2 = "../data/temp_file.txt" # Example path (create the directory/file if needed)
  28. filepath3 = "/path/that/does/not/exist" # Example non-existent path
  29. performance1 = measure_filepath_performance(filepath1)
  30. performance2 = measure_filepath_performance(filepath2)
  31. performance3 = measure_filepath_performance(filepath3)
  32. if performance1 is not None:
  33. print(f"Average time for {filepath1}: {performance1:.6f} seconds")
  34. if performance2 is not None:
  35. print(f"Average time for {filepath2}: {performance2:.6f} seconds")
  36. if performance3 is not None:
  37. print(f"Average time for {filepath3}: {performance3:.6f} seconds")

Add your comment