在Ubuntu系统中进行ThinkPHP性能测试前,需确保环境与生产环境一致,避免因环境差异导致结果偏差。基础环境配置包括:
Apache Bench是Linux自带的轻量级压力测试工具,适合快速测试接口的QPS(每秒查询数)、平均响应时间等基础指标。
sudo apt install apache2-utils安装;-c 100)发送1000次请求(-n 1000)到指定接口:ab -n 1000 -c 100 http://localhost:8000/api/test
-p指定数据文件(如post_data.txt),-T指定Content-Type:ab -n 1000 -c 100 -p post_data.txt -T "application/json" http://localhost:8000/api/test
-k参数启用HTTP Keep-Alive,模拟持久连接:ab -n 1000 -c 100 -k http://localhost:8000/api/test
Apache JMeter是功能强大的图形化压力测试工具,支持复杂场景模拟(如用户登录、数据库操作)、实时结果监控和报告生成,适合对ThinkPHP应用进行全面性能评估。
bin目录,运行./jmeter启动;localhost)、端口(8000)、路径(/api/test)、请求方法(GET/POST);sysbench是多线程系统评测工具,可用于评估Ubuntu服务器的CPU、内存、磁盘I/O等底层资源性能,为ThinkPHP性能瓶颈分析提供基础数据。
sudo apt install sysbench;--cpu-max-prime=20000表示最大素数为20000):sysbench cpu --cpu-max-prime=20000 run
--memory-block-size=1K表示块大小为1KB,--memory-total-size=1G表示总大小为1GB):sysbench memory --memory-block-size=1K --memory-total-size=1G run
--file-total-size=1G表示创建1GB测试文件):sysbench fileio --file-total-size=1G --file-test-mode=rndrw prepare && sysbench fileio --file-total-size=1G --file-test-mode=rndrw run && sysbench fileio --file-total-size=1G cleanup
通过PHP编写自定义性能测试脚本,可针对性测试ThinkPHP应用的特定功能(如数据库查询、缓存操作),获取更细粒度的性能数据。
Benchmark.php文件,记录请求的执行时间和内存使用:<?php
class ThinkPHPBenchmark {
private $startTime;
private $memoryUsage;
public function start() {
$this->startTime = microtime(true);
$this->memoryUsage = memory_get_usage();
return $this;
}
public function end() {
$endTime = microtime(true);
$endMemory = memory_get_usage();
return [
'execution_time' => round(($endTime - $this->startTime) * 1000, 2) . 'ms', // 执行时间(毫秒)
'memory_usage' => round(($endMemory - $this->memoryUsage) / 1024, 2) . 'KB', // 内存使用增量(KB)
'peak_memory' => round(memory_get_peak_usage() / 1024, 2) . 'KB' // 峰值内存(KB)
];
}
}
// 使用示例:测试数据库查询性能
$benchmark = new ThinkPHPBenchmark();
$benchmark->start();
// 执行ThinkPHP数据库查询(如User模型查询)
$users = \app\model\User::where('status', 1)->limit(100)->select();
$result = $benchmark->end();
print_r($result);
microtime(true)记录开始/结束时间,memory_get_usage()记录内存使用,可扩展为批量测试多个接口或功能。性能测试后,需通过监控工具定位瓶颈(如慢SQL、高CPU占用),常用工具包括:
top(实时查看进程CPU/内存占用)、vmstat(报告进程、内存、I/O等活动)、iostat(监控磁盘I/O负载)、netstat(查看网络连接状态);app_debug设为true),查看SQL日志(runtime/log目录)和请求追踪信息;根据测试结果,针对性优化ThinkPHP应用性能:
app_debug设为false,避免不必要的错误日志和调试信息;app_trace设为true),分析慢SQL(如未加索引、复杂JOIN),添加合适的索引;php.ini中开启);worker_processes(设为CPU核心数)、worker_connections(设为1024+);Apache调整MaxRequestWorkers(设为150+)。