-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
62 lines (51 loc) · 1.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
'use strict';
const path = require('path');
const caller = require('caller');
const Worker = require('./lib/worker.js');
const Profiler = require('./lib/profiler.js');
/**
* Measures the impact of running a certain script on your system.
* Monitors the cpu and memory usage of the whole tree of processes generated by
* the script provided.
* @public
* @param {string} code The source code to test.
* @param {Object} [options] Optional configurations.
* @param {number} [options.interval=125] Sampling interval in milliseconds.
* @param {string} [options.cwd=caller] CWD for the script.
* @return {Promise.<Object>} An object containing the results.
*/
async function sympact(code, options) {
if (typeof code !== 'string') {
throw new TypeError("The 'code' paramater must a string'");
}
if (typeof options === 'undefined') {
options = {};
}
if (typeof options !== 'object') {
throw new TypeError("The 'options' paramater must an object'");
}
const interval = options.interval || 125;
const cwd = options.cwd || path.dirname(caller());
if (interval < 1) {
throw new TypeError("The 'interval' paramater must be greater than 0'");
}
return new Promise((resolve, reject) => {
const slave = new Worker(code, cwd);
const probe = new Profiler(slave.pid(), interval);
slave.on('ready', async () => {
await probe.watch();
slave.run();
});
slave.on('after', async (start, end) => {
await probe.unwatch();
slave.kill();
resolve(probe.report(start, end));
});
slave.on('error', async err => {
await probe.unwatch();
slave.kill();
reject(err);
});
});
}
module.exports = sympact;