我正在使用具有 ActiveRecord 系统的 PHP 框架。我很快就遇到了 ActiveRecord 的问题,它使用大量内存,并且对于具有大量结果的复杂查询执行时间很长。
对于我的引用页面(生成包含 10,000 个对象的数组的脚本),我设法将内存消耗从 100+ MB 减少到约 15 MB,并将执行时间从 5 秒以上减少到约 1.5 秒。
这两个衡量指标是唯一需要考虑的衡量指标,还是我应该查看通过 PHP 提供的其他指标?
我通过更改将内容存储在对象变量中的函数以动态计算它来实现了大部分改进。因此我担心CPU,因为在我的本地主机上测试不存在CPU短缺...然而,在实际环境中,由于其他请求等原因,CPU不断被使用。但是如何测量PHP中的CPU消耗?
示例:每当实例化事件记录时,都会在每个对象实例内的私有(private)属性中设置字段、规则和关系。我已将其更改为函数,始终编译并返回值,而不是使用对象属性。
让内存来完成:
class Record {
private $relations;
private $fields;
function __construct() {
$this->setRelations();
$this->setFields();
}
private function setRelations() {
// This process of getting predefined relations, checking for correct data,
// and some other calculations is done once, on every construct.
// The result is stored in $this->relations;
// This costs memory!
}
private function setFields() {
// This process of getting predefined fields, checking for correct data,
// and some other calculations is done once, on every construct.
// The result is stored in $this->fields;
// This costs memory!
}
private function getRelations() {
// This is fast. Loading the set relations from memory.
return $this->relations;
}
private function getFields() {
// This is fast. Loading the set relations from memory.
return $this->fields;
}
}
让CPU来做:
class Record {
function __construct() {
// Drop the setter methods. Let the CPU work when using the getters.
}
private function getRelations() {
// This process of getting predefined relations, checking for correct data,
// and some other calculations is done once, on every getFields()
// This costs CPU!
return $relations;
}
private function getFields() {
// This process of getting predefined fields, checking for correct data,
// and some other calculations is done once, on every getFields()
// This costs CPU!
return $fields;
}
}
我的两个主要问题是:
- 什么更好?
- 如何测量 CPU 消耗?
最佳答案
您在这里忘记了一个非常重要的因素:您的数据库。确保它已正确索引。进行查询分析以查看在最坏的情况下检查了多少行。十分之九的是数据库而不是利用它的代码导致了性能问题。
关于php - 执行时间和内存使用率是 PHP 唯一相关的性能指标吗? CPU呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908615/