import time
import hashlib
def validate_file_performance(filepath, expected_hash, num_iterations=100):
"""
Measures the performance of file content validation against an expected hash.
Args:
filepath (str): The path to the file.
expected_hash (str): The expected SHA-256 hash of the file.
num_iterations (int): The number of validation iterations to perform.
Returns:
tuple: A tuple containing:
- average_time (float): The average time taken per iteration in seconds.
- validation_success (bool): True if all iterations passed validation, False otherwise.
Raises:
FileNotFoundError: If the specified file does not exist.
ValueError: If the expected_hash is not a valid SHA-256 hash.
"""
try:
with open(filepath, "rb") as f:
file_content = f.read()
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {filepath}")
if not isinstance(expected_hash, str) or len(expected_hash) != 64:
raise ValueError("Expected hash must be a 64-character SHA-256 hash.")
try:
calculated_hash = hashlib.sha256(file_content).hexdigest()
except Exception as e:
raise ValueError(f"Error calculating hash: {e}")
if calculated_hash != expected_hash:
print(f"Hash mismatch! Expected: {expected_hash}, Calculated: {calculated_hash}")
return 0.0, False
start_time = time.time()
for _ in range(num_iterations):
calculated_hash = hashlib.sha256(file_content).hexdigest()
if calculated_hash != expected_hash:
print(f"Hash mismatch during iterations! Expected: {expected_hash}, Calculated: {calculated_hash}")
return 0.0, False
end_time = time.time()
total_time = end_time - start_time
average_time = total_time / num_iterations
print(f"Performance validation completed.")
return average_time, True
if __name__ == '__main__':
# Example Usage (replace with your file and expected hash)
filepath = "test_file.txt" #Replace with your file path
expected_hash = "e5b7f39c994b765c9024a8341d544217f8a509d92f8a932a508a777a2460e5b7" # Replace with your expected hash
#Create a test file if it doesn't exist
try:
with open(filepath, "x") as f:
f.write("This is a test file.")
except FileExistsError:
pass
try:
avg_time, success = validate_file_performance(filepath, expected_hash, num_iterations=100)
if success:
print(f"Validation successful. Average time per iteration: {avg_time:.6f} seconds.")
else:
print("Validation failed.")
except (FileNotFoundError, ValueError) as e:
print(f"Error: {e}")
Add your comment