Moodle’s profiling tool
When your software is too slow, you need measurements to tell you which are the slow bits. Tools that do that are called profilers. One of the better profiling tools for PHP is called XHProf. The good news is that it has already been integrated into Moodle, and there is documentation about getting it working. Basically, you just need to install a PHP extension and turn on some options under Admin -> Development -> Profiling.