Profiling CLI Commands

Blackfire can profile any code that you need to run on the command line. It is made easy thanks to the blackfire utility that is bundled with the Blackfire Agent.

Profiling Simple CLI Scripts

Profiling a PHP script is a matter of prefixing your command with blackfire run:

1
2
$ blackfire run php my-script.php
$ blackfire run php my-script.php --your-script-options and arguments

At the end of the execution, blackfire outputs the URL where the profile can be found (this can be hidden by passing the -q option.)

To get more accurate results, you can also take several samples via the --samples option (only do that if you are sure that two successive calls to your script does the same thing without unwanted side effects):

1
$ blackfire --samples 10 run php my-script.php

References

Create a reference profile by passing the --new-reference option:

1
$ blackfire --new-reference run php my-script.php

Compare a profile to a reference profile by passing its id (the id is part of the output of the previous command or available on the web UI) via --reference:

1
$ blackfire --reference=7 run php my-script.php

If you want to collaborate on performance, you can send a profile directly to an environment by passing the environment server id (or the environment name) via the --env option (or --team on previous versions of blackfire):

1
$ blackfire --env=example.com run php my-script.php

If you don't remember the reference profile you need to use or the environment name, use the --interactive option:

1
$ blackfire --interactive run php my-script.php

JSON Output

You can easily integrate Blackfire results into your own tools by using the --json option to get a JSON representation of a profile:

1
$ blackfire --json run php my-script.php

The resources consumed are available under the envelope entry; keys are the dimensions:

  • pmu: Peak Memory Usage (in bytes);
  • nw: Network (in bytes);
  • wt: Wall Clock Time (in microseconds);
  • cpu: CPU time (in microseconds);
  • io: I/O time (in microseconds).

Profiling Part of a CLI Script

Blackfire automatically instruments your code, but sometimes, you might want to focus the profiling on only part of the code. That's possible when opting for manual instrumentation via the PHP SDK.

After instrumenting your code, use the blackfire utility as above to profile your application. When not using Blackfire, all calls are converted to noops.

Profiling Consumers and Daemons

Consumers and Daemons are special as they run for a very long time (or indefinitely for daemons). In that case, using automatic instrumentation and the blackfire utility cannot work. Fortunately, the PHP SDK provides an API that lets you easily profile consumers and daemons.