const crypto = require('crypto');
const { performance } = require('perf_hooks');
// Data to hash (1MB of random data)
const data = crypto.randomBytes(1024 * 1024);
// Function to measure hash algorithm performance
function measureHashPerformance(algorithm, iterations = 100) {
// Ensure the algorithm is supported
try {
crypto.createHash(algorithm);
} catch (error) {
return { algorithm, error: error.message };
}
const startTime = performance.now();
for (let i = 0; i < iterations; i++) {
const hash = crypto.createHash(algorithm);
hash.update(data);
hash.digest();
}
const endTime = performance.now();
const totalTime = endTime - startTime;
return {
algorithm,
iterations,
totalTimeMs: totalTime.toFixed(2),
timePerHashMs: (totalTime / iterations).toFixed(4),
hashesPerSecond: Math.floor(iterations / (totalTime / 1000))
};
}
// Test various hash algorithms
const algorithms = ['md5', 'sha1', 'sha256', 'sha512', 'sha3-256', 'sha3-512'];
const results = [];
console.log('Measuring hash performance for 1MB of data...');
algorithms.forEach(algorithm => {
results.push(measureHashPerformance(algorithm));
});
// Display results in a table format
console.table(results);
// Display relative performance (normalized to the fastest algorithm)
console.log('\nRelative Performance:');
// Find the fastest algorithm
const fastest = results.reduce((prev, current) => {
if (current.error) return prev;
return (prev && prev.hashesPerSecond > current.hashesPerSecond) ? prev : current;
}, null);
if (fastest) {
results.forEach(result => {
if (!result.error) {
const relativeSpeed = (result.hashesPerSecond / fastest.hashesPerSecond).toFixed(2);
console.log(`${result.algorithm}: ${relativeSpeed}x (${result.hashesPerSecond} hashes/sec)`);
} else {
console.log(`${result.algorithm}: Error - ${result.error}`);
}
});
}