The PerfMeasurement.jsm JavaScript code module lets you take detailed performance measurements of your code.

Note: The PerfMeasurement.jsm JavaScript code module can only be used from chrome -- that is, from within the application itself or an add-on.

The first thing you need to do is to import the module into your scope:

Components.utils.import("resource://gre/modules/PerfMeasurement.jsm")

You can then create a PerfMeasurement object. You give the constructor a bit-mask of events you're interested in; see

Note: At present, PerfMeasurement.jsm is only functional on Linux, but it is planned to add support for Windows (bug 583322) and OSX (bug 583323) as well, and we welcome patches for other operating systems.

For instance, let's measure instructions executed, cache references, and cache misses:

let monitor = new PerfMeasurement(PerfMeasurement.CPU_CYCLES |
              PerfMeasurement.CACHE_REFERENCES | PerfMeasurement.CACHE_MISSES);

This creates a new PerfMeasurement object, configured to record the specified event types. it doesn't, however, start to record data.

Now we want to benchmark a function that is pretty fast (but not fast enough), so we run it several thousand times:

for (let i = 0; i < 10000; i++) {
  set_up_some_state();
  monitor.start();
  code_to_be_benchmarked();
  monitor.stop();
  clean_up_afterward();
}

We call the PerfMeasurement object's start() method when we want to start recording, and stop() when we want to stop recording. This lets us record information only for the specific code section we want to measure.

Since we enable monitoring immediately before calling  code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured.  The monitor object automatically accumulates counts over start/stop cycles (that is, it doesn't automatically zero the counters each time you start recording).  When you're done benchmarking, you can read out each of the counters you asked for as properties:

let report = "CPU cycles:   " + monitor.cpu_cycles + "\n" +
             "Cache refs:   " + monitor.cache_references + "\n" +
             "Cache misses: " + monitor.cache_misses + "\n";
monitor.reset();
alert(report);

The reset() method clears all of the enabled counters, as you might expect.  When you're done with your measurements, just let the monitor object go out of scope.

See also