|
| 1 | +import {ApplicationRef, LifeCycle} from 'angular2/angular2'; |
| 2 | +import {isPresent, NumberWrapper} from 'angular2/src/core/facade/lang'; |
| 3 | +import {performance, window} from 'angular2/src/core/facade/browser'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Entry point for all Angular debug tools. This object corresponds to the `ng` |
| 7 | + * global variable accessible in the dev console. |
| 8 | + */ |
| 9 | +export class AngularTools { |
| 10 | + profiler: AngularProfiler; |
| 11 | + |
| 12 | + constructor(appRef: ApplicationRef) { this.profiler = new AngularProfiler(appRef); } |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * Entry point for all Angular profiling-related debug tools. This object |
| 17 | + * corresponds to the `ng.profiler` in the dev console. |
| 18 | + */ |
| 19 | +export class AngularProfiler { |
| 20 | + lifeCycle: LifeCycle; |
| 21 | + |
| 22 | + constructor(appRef: ApplicationRef) { this.lifeCycle = appRef.injector.get(LifeCycle); } |
| 23 | + |
| 24 | + /** |
| 25 | + * Exercises change detection in a loop and then prints the average amount of |
| 26 | + * time in milliseconds how long a single round of change detection takes for |
| 27 | + * the current state of the UI. It runs a minimum of 5 rounds for a minimum |
| 28 | + * of 500 milliseconds. |
| 29 | + * |
| 30 | + * Optionally, a user may pass a `config` parameter containing a map of |
| 31 | + * options. Supported options are: |
| 32 | + * |
| 33 | + * `record` (boolean) - causes the profiler to record a CPU profile while |
| 34 | + * it exercises the change detector. Example: |
| 35 | + * |
| 36 | + * ``` |
| 37 | + * ng.profiler.timeChangeDetection({record: true}) |
| 38 | + * ``` |
| 39 | + */ |
| 40 | + timeChangeDetection(config: any) { |
| 41 | + var record = isPresent(config) && config['record']; |
| 42 | + var profileName = 'Change Detection'; |
| 43 | + if (record) { |
| 44 | + window.console.profile(profileName); |
| 45 | + } |
| 46 | + var start = window.performance.now(); |
| 47 | + var numTicks = 0; |
| 48 | + while (numTicks < 5 || (window.performance.now() - start) < 500) { |
| 49 | + this.lifeCycle.tick(); |
| 50 | + numTicks++; |
| 51 | + } |
| 52 | + var end = window.performance.now(); |
| 53 | + if (record) { |
| 54 | + // need to cast to <any> because type checker thinks there's no argument |
| 55 | + // while in fact there is: |
| 56 | + // |
| 57 | + // https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd |
| 58 | + (<any>window.console.profileEnd)(profileName); |
| 59 | + } |
| 60 | + var msPerTick = (end - start) / numTicks; |
| 61 | + window.console.log(`ran ${numTicks} change detection cycles`); |
| 62 | + window.console.log(`${NumberWrapper.toFixed(msPerTick, 2)} ms per check`); |
| 63 | + } |
| 64 | +} |
0 commit comments