作为一名程序员最好的部分之一就是似乎总是有更好的方法来做事。一个简单的代码调整可以显着提高 Web 应用程序的执行时间。您的应用程序执行得越快,您释放宝贵的服务器资源的速度就越快。
优化现有基于 PHP 的 Web 应用程序以提高速度的第一步是了解网站的哪些部分需要改进。您的 MySQL 查询是否花费太长时间?你在使用高效的功能吗?您是否在使用不必要的服务器资源?
在我的 Web 应用程序中,我使用计时器类来衡量查询、函数和整个页面需要多长时间才能完成。
函数
class timer { var $start; var $pause_time; /* start the timer */ function timer($start = 0) { if($start) { $this->start(); } } /* start the timer */ function start() { $this->start = $this->get_time(); $this->pause_time = 0; } /* pause the timer */ function pause() { $this->pause_time = $this->get_time(); } /* unpause the timer */ function unpause() { $this->start += ($this->get_time() - $this->pause_time); $this->pause_time = 0; } /* get the current timer value */ function get($decimals = 8) { return round(($this->get_time() - $this->start),$decimals); } /* format the time in seconds */ function get_time() { list($usec,$sec) = explode(' ', microtime()); return ((float)$usec + (float)$sec); } }
用法
$timer = new timer(1); // constructor starts the timer, so no need to do it ourselves /* ... mysql query ... */ $query_time = $timer->get(); /* ... page processing ... */ $processing_time = $timer->get();
输出
一旦您知道您网站的哪些区域需要改进,如果您的代码经过良好的注释和组织,那么使您的代码更高效会很容易。使用计时器——您注意到您网站的哪些区域需要改进,您是如何优化代码的?我很想听听您的问题和解决方案!