Skip to content

Commit 9043bf3

Browse files
ofrobotsnolanmar511
authored andcommitted
feat: automatically profile when --require'd (#8)
1 parent 65acd4f commit 9043bf3

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

ts/src/index.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@
1313
* See the License for the specific language governing permissions and
1414
* limitations under the License.
1515
*/
16+
import {writeFileSync} from 'fs';
17+
import {gzipSync} from 'zlib';
18+
19+
import {perftools} from '../../proto/profile';
20+
1621
import * as heapProfiler from './heap-profiler';
1722
import * as timeProfiler from './time-profiler';
1823

@@ -28,3 +33,16 @@ export const heap = {
2833
stop: heapProfiler.stop,
2934
profile: heapProfiler.profile,
3035
};
36+
37+
// If loaded with --require, start profiling.
38+
if (module.parent && module.parent.id === 'internal/preload') {
39+
const stop = time.start();
40+
process.on('exit', () => {
41+
// The process is going to terminate imminently. All work here needs to
42+
// be synchronous.
43+
const profile = stop();
44+
const buffer = perftools.profiles.Profile.encode(profile).finish();
45+
const compressed = gzipSync(buffer);
46+
writeFileSync(`pprof-profile-${process.pid}.pb.gz`, compressed);
47+
});
48+
}

ts/src/time-profiler.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ import {setSamplingInterval, startProfiling, stopProfiling} from './time-profile
2222

2323
let profiling = false;
2424

25+
const DEFAULT_INTERVAL_MICROS: Microseconds = 1000;
26+
2527
type Microseconds = number;
2628
type Milliseconds = number;
2729

@@ -35,14 +37,16 @@ export interface TimeProfilerOptions {
3537
}
3638

3739
export async function profile(options: TimeProfilerOptions) {
38-
const stop =
39-
start(options.intervalMicros || 1000, options.name, options.sourceMapper);
40+
const stop = start(
41+
options.intervalMicros || DEFAULT_INTERVAL_MICROS, options.name,
42+
options.sourceMapper);
4043
await delay(options.durationMillis);
4144
return stop();
4245
}
4346

4447
export function start(
45-
intervalMicros: Microseconds, name?: string, sourceMapper?: SourceMapper) {
48+
intervalMicros: Microseconds = DEFAULT_INTERVAL_MICROS, name?: string,
49+
sourceMapper?: SourceMapper) {
4650
if (profiling) {
4751
throw new Error('already profiling');
4852
}

0 commit comments

Comments
 (0)