
本文介绍如何在 php 中准确测量 aes(或其他算法如 twofish)加解密操作的执行时间,涵盖高精度计时原理、完整可运行示例、注意事项及性能优化建议。
本文介绍如何在 php 中准确测量 aes(或其他算法如 twofish)加解密操作的执行时间,涵盖高精度计时原理、完整可运行示例、注意事项及性能优化建议。
在 PHP 中精确测量加密/解密耗时,关键在于使用 microtime(true) 获取浮点型高精度时间戳(单位:秒,精度达微秒级),并通过差值计算实际执行时间。直接调用 microtime() 两次并相减是最可靠、开销最小的方式,避免了 time() 等低精度函数或外部工具引入的误差。
以下是一个完整的、可直接运行的示例,包含 AES-256-CBC 加密与对应解密流程,并分别统计单次及多次平均耗时:
<?php
// 启用错误报告便于调试(生产环境请关闭)
error_reporting(E_ALL);
ini_set('display_errors', 1);
function encrypt($plaintext, $password) {
$method = 'AES-256-CBC';
$key = hash('sha256', $password, true); // 32字节密钥
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed: ' . openssl_error_string());
}
return ['ciphertext' => $ciphertext, 'iv' => $iv, 'key' => $key];
}
function decrypt($data, $password) {
$method = 'AES-256-CBC';
$key = hash('sha256', $password, true);
$ciphertext = $data['ciphertext'];
$iv = $data['iv'];
$plaintext = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($plaintext === false) {
throw new RuntimeException('Decryption failed: ' . openssl_error_string());
}
return $plaintext;
}
// 测试数据
$plaintext = str_repeat('Hello, PHP Security!', 100); // 约2KB明文
$password = 'my_secure_password_2024';
// ? 测量单次加密耗时
$start = microtime(true);
$encResult = encrypt($plaintext, $password);
$encryptTime = microtime(true) - $start;
// ? 测量单次解密耗时
$start = microtime(true);
$decrypted = decrypt($encResult, $password);
$decryptTime = microtime(true) - $start;
// ? 验证正确性(可选但强烈推荐)
if ($decrypted !== $plaintext) {
echo "❌ 解密验证失败:原始文本与还原文本不一致。\n";
} else {
echo "✅ 加解密验证通过。\n";
}
// 输出结果(保留6位小数,单位:秒)
printf("? 单次加密耗时: %.6f 秒\n", $encryptTime);
printf("? 单次解密耗时: %.6f 秒\n", $decryptTime);
printf("? 吞吐量估算: %.2f KB/s\n", strlen($plaintext) / ($encryptTime + $decryptTime) / 1024);
// ? 多次运行取平均值(消除瞬时抖动,更贴近真实性能)
$iterations = 1000;
$totalEncryptTime = 0;
$totalDecryptTime = 0;
for ($i = 0; $i < $iterations; $i++) {
$start = microtime(true);
$enc = encrypt($plaintext, $password);
$totalEncryptTime += microtime(true) - $start;
$start = microtime(true);
decrypt($enc, $password);
$totalDecryptTime += microtime(true) - $start;
}
printf("\n? %d 次平均耗时:\n", $iterations);
printf(" 加密平均: %.6f 秒/次\n", $totalEncryptTime / $iterations);
printf(" 解密平均: %.6f 秒/次\n", $totalDecryptTime / $iterations);⚠️ 重要注意事项:
- 勿用 -microtime(true) 技巧:原答案中 -$microtime(true) 再累加的方式易受浮点精度和时钟漂移影响,逻辑冗余且可读性差,应始终采用 end - start 的直观写法;
- Twofish 支持说明:PHP 原生 openssl_* 不支持 Twofish;如需测试,须借助 libsodium(sodium_crypto_secretbox())或第三方扩展(如 php-tweetnacl),并确保环境已正确安装;
- 环境一致性:禁用 OPcache 预热、关闭 Xdebug(xdebug.mode=off)、避免后台高负载任务,以保障测量稳定性;
- 冷启动影响:首次调用 openssl_encrypt 可能触发 OpenSSL 初始化开销,建议预热 1–2 次再正式计时;
- 安全提醒:示例中为演示简化了密钥派生(仅用 hash()),生产环境务必使用 password_hash() / sodium_crypto_pwhash() 等抗暴力破解方案。
掌握精准计时方法后,你不仅能横向对比 AES、ChaCha20 或国密 SM4 等算法性能,还可评估不同密钥长度、填充模式或硬件加速(如 Intel AES-NI)的实际收益。将计时逻辑封装为独立 Benchmark 工具类,是构建安全中间件或密码学组件的必备实践。
立即学习“PHP免费学习笔记(深入)”;



















