Yesterday I hit a tricky situation with profiling, and I just wanted to write it up where other people might see what I learned.
The situation was that since we upgraded our development environment to Moodle 3.8.2 (from 3.7.x) some of our Behat tests were failing because of hitting the PHP 30-second time-limit, and this was happening in in the minfiy library. We realised that this was it minifiying the CSS for our theme.
Profiling theme/styles.php
So, I wanted to profile (as in https://docs.moodle.org/dev/Profiling_PHP) theme/styles.php. However, that did not work, because that script sets ABORT_AFTER_CONFIG for performance reasons.
This caused Mark Johnson to tell me about $CFG->earlyprofilingenabled = true; which is worth knowing about. (The link there goes to where it is documented in config-dist.php.) However, that did no good. It still does not let you profile ABORT_AFTER_CONFIG scripts.
Then, thanks to a hint from Andrew Nicols, I just hacked the code in theme/styles.php to remove the ABORT_AFTER_CONFIG. It is not quite as simple as that, because the script uses functions like min_clean_param, so I then needed to add a manual require_once of lib/configonlylib.php, and also, lower down the script where it goes in to define('ABORT_AFTER_CONFIG_CANCEL', true);. I had to comment out that bit to prevent errors.
However, with those things done I got the profiling done, and found that almost all of the 40-second execution time (when it was re-building the CSS after the theme cache had been cleared) was due to calls from the minify library to preg_match and preg_replace.
Finding the issue in minify
So, then the question was, which preg calls in minify were causing the bad performance? The only way I could think of to do this was to add some debug code in the library, to count and time the preg_calls with different regexes. That lead to the first half of this patch. For each regex match, we write the number of times it is used, and the total time taken to a comment at the top of the minified PHP.
Then, for using that, it was a major pain that Moodle agressively caches the mified CSS. So I went through the relevant code relentlessly hacking if statements so that it never used the caches and always did the minifying. This meant that I could open the direct URL to the CSS in my browser, and just keep pressing F5 to reload as I changed things. That is the second part of the patch.
(As an aside, it is often worth putting in a little bit of extra effort in code like this whch you will later throw away, to make the feedback cycle as short as possible while you are working on the code changes that you want to keep.)
So, anyway, it then became really obvious which the problem regex was, and I was able to fix it. For the rest of the story (which is not finished yet), see https://github.com/matthiasmullie/minify/issues/317 and MDL-68191
Hope this is at least vaguely useful/interesting to someone.