import time
import os
def measure_filepath_performance(filepath, num_iterations=1000):
"""
Measures the performance of accessing a file path.
Args:
filepath (str): The file path to measure.
num_iterations (int): The number of times to access the path.
Returns:
float: The average time in seconds to access the file path.
Returns None if the file doesn't exist.
"""
start_time = time.time()
try:
for _ in range(num_iterations):
os.path.exists(filepath) # Check if the path exists
except FileNotFoundError:
print(f"Error: File not found: {filepath}")
return None
end_time = time.time()
elapsed_time = end_time - start_time
average_time = elapsed_time / num_iterations
return average_time
if __name__ == '__main__':
# Example usage
filepath1 = "." # Current directory
filepath2 = "../data/temp_file.txt" # Example path (create the directory/file if needed)
filepath3 = "/path/that/does/not/exist" # Example non-existent path
performance1 = measure_filepath_performance(filepath1)
performance2 = measure_filepath_performance(filepath2)
performance3 = measure_filepath_performance(filepath3)
if performance1 is not None:
print(f"Average time for {filepath1}: {performance1:.6f} seconds")
if performance2 is not None:
print(f"Average time for {filepath2}: {performance2:.6f} seconds")
if performance3 is not None:
print(f"Average time for {filepath3}: {performance3:.6f} seconds")
Add your comment