├── .babelrc ├── .github └── workflows │ └── test.yml ├── .gitignore ├── .jshintrc ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── index.js ├── karma.conf.js ├── package-lock.json ├── package.json └── test ├── bdd.js ├── int.js └── unit.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "targets": { 5 | "browsers": ["chrome > 65"] 6 | } 7 | }] 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Node.js CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | node-version: [10.x, 12.x, 14.x, 15.x, 16.x] 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: browser-actions/setup-chrome@latest 18 | - run: chrome --version 19 | - name: Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v2 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | - name: Install dependencies 24 | run: npm ci 25 | - run: | 26 | export DISPLAY=:99.0 27 | CHROMIUM_BIN=$(which chrome) npm test 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Node template 3 | # Logs 4 | logs 5 | *.log 6 | 7 | # Runtime data 8 | pids 9 | *.pid 10 | *.seed 11 | 12 | # Directory for instrumented libs generated by jscoverage/JSCover 13 | lib-cov 14 | 15 | # Coverage directory used by tools like istanbul 16 | coverage 17 | 18 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 19 | .grunt 20 | 21 | # node-waf configuration 22 | .lock-wscript 23 | 24 | # Compiled binary addons (http://nodejs.org/api/addons.html) 25 | build/Release 26 | 27 | # Dependency directory 28 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 29 | node_modules 30 | 31 | # editor 32 | .idea/ 33 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "asi": false, 3 | "bitwise": true, 4 | "camelcase": false, 5 | "curly": true, 6 | "debug": true, 7 | "devel": true, 8 | "eqeqeq": true, 9 | "esnext": true, 10 | "evil": false, 11 | "expr": true, 12 | "forin": true, 13 | "freeze": false, 14 | "funcscope": false, 15 | "globalstrict": false, 16 | "latedef": false, 17 | "maxcomplexity": 15, 18 | "maxdepth": 5, 19 | "maxerr": 50, 20 | "maxparams": 7, 21 | "mocha": true, 22 | "newcap": false, 23 | "noarg": true, 24 | "node": true, 25 | "noempty": true, 26 | "nonbsp": true, 27 | "undef": false, 28 | "unused": false, 29 | "globals": { 30 | "require": true, 31 | "mocha": true, 32 | "Promise": true, 33 | "context": true 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | .idea 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | sudo: required 3 | addons: 4 | chrome: stable 5 | language: node_js 6 | node_js: 7 | - '8' 8 | - '10' 9 | - '12' 10 | - '14' 11 | - '16' 12 | before_install: 13 | - export CHROME_BIN=chromium-browser 14 | - export DISPLAY=:99.0 15 | - sh -e /etc/init.d/xvfb start 16 | - npm install -g npm 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Alexandru Savin 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Description 2 | ----------- 3 | 4 | [![Greenkeeper badge](https://badges.greenkeeper.io/alexandrusavin/exectimer.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/alexandrusavin/exectimer.png?branch=master)](https://travis-ci.org/alexandrusavin/exectimer) 5 | 6 | Very simple but powerful nodejs and browser module build to track execution time with a resolution of nanoseconds. 7 | 8 | Install 9 | ------- 10 | 11 | Simply run: 12 | ``` 13 | npm install exectimer 14 | ``` 15 | 16 | Usage 17 | ----- 18 | 19 | ### Example 20 | 21 | #### Wrapping generator 22 | ```javascript 23 | const t = require('exectimer'); 24 | const Tick = t.Tick; 25 | 26 | const promises = []; 27 | for(var i = 0; i < 10; i++) { 28 | const functionExecution = Tick.wrap(function* myFunction() { 29 | yield Promise.resolve(true); 30 | }); 31 | 32 | promises.push(functionExecution); 33 | } 34 | 35 | // After all ticks are finished 36 | Promise.all(promises).then(() => { 37 | // display the results 38 | var results = t.timers.myFunction; 39 | console.log(results.parse(results.duration())); // total duration of all ticks 40 | console.log(results.parse(results.min())); // minimal tick duration 41 | console.log(results.parse(results.max())); // maximal tick duration 42 | console.log(results.parse(results.mean())); // mean tick duration 43 | console.log(results.parse(results.median())); // median tick duration 44 | }); 45 | ``` 46 | 47 | #### Wrapping 48 | ```javascript 49 | const t = require('exectimer'); 50 | const Tick = t.Tick; 51 | 52 | 53 | for(var i = 0; i < 10; i++) { 54 | Tick.wrap(function myFunction(done) { 55 | setTimeout(function() { 56 | done(); 57 | }, 10); 58 | }); 59 | } 60 | 61 | // Display the results 62 | var results = t.timers.myFunction; 63 | setTimeout(() => { 64 | console.log(results.parse( 65 | results.duration() 66 | )); // total duration of all ticks 67 | console.log(results.parse( 68 | results.min() 69 | )); // minimal tick duration 70 | console.log(results.parse( 71 | results.max() 72 | )); // maximal tick duration 73 | console.log(results.parse( 74 | results.mean() 75 | )); // mean tick duration 76 | console.log(results.parse( 77 | results.median() 78 | )); // median tick duration 79 | }, 101); 80 | 81 | ``` 82 | 83 | #### Instantiating the ticks yourself 84 | 85 | ```javascript 86 | const t = require('exectimer'); 87 | const Tick = t.Tick; 88 | 89 | for(var i = 0; i < 10; i++) { 90 | // unique contexts to avoid aliasing (#9) 91 | (function () { 92 | var tick = new Tick("myFunction"); 93 | tick.start(); 94 | 95 | setTimeout(function() { 96 | tick.stop(); 97 | }, Math.random() * 10); 98 | })(); 99 | } 100 | 101 | // Display the results 102 | var results = t.timers.myFunction; 103 | setTimeout(() => { 104 | console.log(results.parse( 105 | results.duration() 106 | )); // total duration of all ticks 107 | console.log(results.parse( 108 | results.min() 109 | )); // minimal tick duration 110 | console.log(results.parse( 111 | results.max() 112 | )); // maximal tick duration 113 | console.log(results.parse( 114 | results.mean() 115 | )); // mean tick duration 116 | console.log(results.parse( 117 | results.median() 118 | )); // median tick duration 119 | }, 101); 120 | 121 | ``` 122 | 123 | API 124 | --- 125 | 126 | ### Tick 127 | A tick is used to measure the difference between two execution points. All ticks are than used to calculate the average, median, min, max etc. 128 | Takes the name of the timer as an argument. 129 | 130 | #### Tick.wrap() 131 | 132 | **Arguments** 133 | 134 | 1. [`name`] *(String)* Name of the function 135 | 1. `callback` *(Function)* Function for which to calculate the duration 136 | 137 | - **callback** Can be a function or a generator 138 | 1. [`done`] *(Function)* Should be passed if function is asynchronous 139 | 140 | Static function that takes a name and a function as arguments. If the name is omitted than it tries to read the name of the function or it just uses "anon". 141 | If `done` function is not requested than it presumes that the call is synchronous. 142 | It also accepts a generator function in which case `done` function is not necessary. 143 | 144 | #### Tick.prototype.start() 145 | Starts the timer of this tick. 146 | 147 | #### Tick.prototype.stop() 148 | Stops the timer of this tick. 149 | 150 | ###Timers 151 | Array of timers. Each timer has methods to calculate the various metrics. When a tick is created, it is pushed into the 152 | timer with name that was passed to the ticker in the constructor. 153 | 154 | ``` 155 | var tick = new t.Tick("TIMER"); 156 | 157 | tick.start(); 158 | // Do some processing 159 | tick.stop(); 160 | 161 | var myTimer = t.timers.TIMER; 162 | 163 | console.log("It took: " + myTimer.duration()); 164 | ``` 165 | You can name your timer however you want. 166 | 167 | #### Timers.TIMER.min() 168 | Get the shortest tick. 169 | 170 | #### Timers.TIMER.max() 171 | Get the longest tick. 172 | 173 | #### Timers.TIMER.mean() 174 | Get the average tick. 175 | 176 | #### Timers.TIMER.median() 177 | Get the median tick. 178 | 179 | #### Timers.TIMER.duration() 180 | Get the total duration of all ticks. 181 | 182 | #### Timers.TIMER.count() 183 | Get the number of ticks. 184 | 185 | #### Timers.TIMER.parse() 186 | Parse the output of the previous methods from nanoseconds to us, ms, ns or seconds. 187 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const co = require('co'); 4 | const hrtime = require('browser-process-hrtime'); 5 | 6 | /** 7 | * Contains all timers. 8 | * @type {{}} 9 | */ 10 | const timers = {}; 11 | 12 | /** 13 | * Timers factory object. 14 | * @param name 15 | * @returns {*} 16 | */ 17 | const timer = function (name) { 18 | if (typeof timers[name] === 'undefined') { 19 | timers[name] = { 20 | ticks: [], 21 | 22 | /** 23 | * Get the median of all ticks. 24 | * @returns {*} 25 | */ 26 | median: function () { 27 | if (this.ticks.length > 1) { 28 | const sorted = this.ticks.slice(0).sort(function (a, b) { 29 | return a && b && (a.getDiff() - b.getDiff()) || 0; 30 | }); 31 | 32 | const l = sorted.length; 33 | const half = Math.floor(l / 2); 34 | 35 | 36 | if (l % 2) { 37 | return sorted[half].getDiff(); 38 | } else { 39 | return (sorted[half - 1].getDiff() + sorted[half].getDiff()) / 2; 40 | } 41 | } else { 42 | return this.ticks[0].getDiff(); 43 | } 44 | }, 45 | 46 | /** 47 | * Get the average duration of all ticks. 48 | * @returns {number} 49 | */ 50 | mean: function () { 51 | return this.duration() / this.ticks.length; 52 | }, 53 | 54 | /** 55 | * Get the duration of all ticks. 56 | * @returns {number} 57 | */ 58 | duration: function () { 59 | let sum = 0; 60 | for (let i = 0, l = this.ticks.length; i < l; i++) { 61 | sum += this.ticks[i].getDiff(); 62 | } 63 | return sum; 64 | }, 65 | 66 | /** 67 | * Get the shortest tick. 68 | * @returns {number} 69 | */ 70 | min: function () { 71 | let min = this.ticks[0].getDiff(); 72 | this.ticks.forEach(function (tick) { 73 | if (tick.getDiff() < min) { 74 | min = tick.getDiff(); 75 | } 76 | }); 77 | 78 | return min; 79 | }, 80 | 81 | /** 82 | * Get the longest tick. 83 | * @returns {number} 84 | */ 85 | max: function () { 86 | let max = 0; 87 | this.ticks.forEach(function (tick) { 88 | if (tick.getDiff() > max) { 89 | max = tick.getDiff(); 90 | } 91 | }); 92 | 93 | return max; 94 | }, 95 | 96 | /** 97 | * Get the number of ticks. 98 | * @returns {Number} 99 | */ 100 | count: function () { 101 | return Object.keys(this.ticks).length; 102 | }, 103 | 104 | /** 105 | * Parse the numbers nicely. 106 | * @param num 107 | * @returns {string} 108 | */ 109 | parse: function (num) { 110 | if (num < 1e3) { 111 | return num + ' ns'; 112 | } else if (num >= 1e3 && num < 1e6) { 113 | return num / 1e3 + ' us'; 114 | } else if (num >= 1e6 && num < 1e9) { 115 | return num / 1e6 + ' ms'; 116 | } else if (num >= 1e9) { 117 | return num / 1e9 + ' s'; 118 | } 119 | }, 120 | 121 | /** 122 | * Utility function that prints all indicators. 123 | * 124 | * @returns undefined 125 | */ 126 | printResults: function () { 127 | console.log('Total duration: %s', this.parse(this.duration())); 128 | console.log('Min: %s', this.parse(this.min())); 129 | console.log('Max: %s', this.parse(this.max())); 130 | console.log('Mean: %s', this.parse(this.mean())); 131 | console.log('Median: %s', this.parse(this.median())); 132 | } 133 | }; 134 | } 135 | 136 | return timers[name]; 137 | }; 138 | 139 | /** 140 | * Constructor of tick. 141 | * @param name The name of this tick. 142 | * @returns {Tick} 143 | * @constructor 144 | */ 145 | function Tick(name) { 146 | this.name = name; 147 | return this; 148 | } 149 | 150 | Tick.wrap = function (name, callback) { 151 | if (typeof name === 'function') { 152 | callback = name; 153 | name = functionName(callback); 154 | } 155 | 156 | if (name === '') { 157 | name = 'anon'; 158 | } 159 | 160 | const tick = new Tick(name); 161 | tick.start(); 162 | 163 | const done = function () { 164 | tick.stop(); 165 | }; 166 | 167 | if (isGeneratorFunction(callback)) { 168 | return co(callback).then(done, done); 169 | } else if(isFunction(callback)) { 170 | // If done is passed when the callback is declared than we assume is async 171 | return callback(done); 172 | } else { 173 | // Callback is not a function which is not permitted 174 | throw new Error('Tick.wrap expects a callback function parameter'); 175 | } 176 | }; 177 | 178 | /** 179 | * Starts the tick. 180 | */ 181 | Tick.prototype.start = function () { 182 | this.hrstart = hrtime(); 183 | timer(this.name).ticks.push(this); 184 | }; 185 | 186 | /** 187 | * Ends the tick. 188 | */ 189 | Tick.prototype.stop = function () { 190 | this.hrend = hrtime(this.hrstart); 191 | }; 192 | 193 | /** 194 | * Get the duration of the tick. 195 | * @returns Long nanoseconds 196 | */ 197 | Tick.prototype.getDiff = function () { 198 | if(!this.hrend) { 199 | this.stop(); 200 | } 201 | 202 | return this.hrend[0] * 1e9 + this.hrend[1]; 203 | }; 204 | 205 | module.exports = { 206 | timer: timer, 207 | timers: timers, 208 | Tick: Tick 209 | }; 210 | 211 | /** 212 | * Helper function used to retrieve function name. 213 | * @param fun 214 | * @returns {string} 215 | */ 216 | function functionName(fun) { 217 | let ret = fun.toString(); 218 | ret = ret.substr('function '.length); 219 | ret = ret.substr(0, ret.indexOf('(')); 220 | return ret.trim(); 221 | } 222 | 223 | /** 224 | * Check if `obj` is a generator function. 225 | * 226 | * @param {Mixed} value 227 | * @return {Boolean} 228 | * @api private 229 | */ 230 | function isGeneratorFunction(value) { 231 | return typeof value === 'function' && value.constructor.name === 'GeneratorFunction'; 232 | } 233 | 234 | /** 235 | * Helper function used to check is argument is of type function 236 | * @author https://github.com/lodash/lodash/blob/4.16.4/lodash.js#L11590 237 | * @param value 238 | * @returns {boolean} 239 | */ 240 | function isFunction(value) { 241 | // The use of `Object#toString` avoids issues with the `typeof` operator 242 | // in Safari 9 which returns 'object' for typed array and other constructors. 243 | var tag = isObject(value) ? Object.prototype.toString.call(value) : ''; 244 | return tag == '[object Function]' || tag == '[object GeneratorFunction]' || tag == '[object Proxy]'; 245 | } 246 | 247 | /** 248 | * Helper function used to check is argument is of type object 249 | * @author https://github.com/lodash/lodash/blob/4.16.4/lodash.js#L11590 250 | * @param value 251 | * @returns {boolean} 252 | */ 253 | function isObject(value) { 254 | var type = typeof value; 255 | return value != null && (type == 'object' || type == 'function'); 256 | } 257 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | module.exports = (config) => { 2 | config.set({ 3 | basePath: 'test', 4 | frameworks: ['mocha'], 5 | files: [ 6 | 'int.js' 7 | ], 8 | preprocessors: { 9 | './int.js': ['webpack'], 10 | }, 11 | reporters: ['progress', 'mocha'], 12 | webpack: { 13 | devtool: 'inline-source-map' 14 | }, 15 | port: 9876, 16 | colors: true, 17 | customLaunchers: { 18 | Chrome_travis_ci: { 19 | base: 'Chrome', 20 | flags: ['--no-sandbox'] 21 | } 22 | }, 23 | browsers: ['Chrome_travis_ci'], 24 | singleRun: true, 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "exectimer", 3 | "version": "2.2.2", 4 | "description": "Very simple module to calculate block execution time.", 5 | "license": "MIT", 6 | "keywords": [ 7 | "time", 8 | "timer", 9 | "profiler", 10 | "execution", 11 | "performance", 12 | "analysis", 13 | "benchmark" 14 | ], 15 | "homepage": "https://github.com/alexandrusavin/exectimer", 16 | "bugs": "https://github.com/alexandrusavin/exectimer/issues", 17 | "author": { 18 | "name": "Alexandru Savin", 19 | "email": "alexandrusavin@gmail.com" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git://github.com/alexandrusavin/exectimer.git" 24 | }, 25 | "main": "./index", 26 | "scripts": { 27 | "test-unit": "mocha test/unit.js", 28 | "test-bdd": "mocha test/bdd.js", 29 | "test-int": "mocha test/int.js", 30 | "test-browser": "karma start", 31 | "test": "npm run test-unit && npm run test-bdd && npm run test-int && npm run test-browser" 32 | }, 33 | "engines": { 34 | "node": ">=6.0.0" 35 | }, 36 | "devDependencies": { 37 | "async": "^2.6.0", 38 | "babel-core": "^6.26.0", 39 | "babel-loader": "^8.0.0", 40 | "babel-preset-env": "^1.6.1", 41 | "chai": "^4.1.2", 42 | "karma": "^3.1.1", 43 | "karma-babel-preprocessor": "^7.0.0", 44 | "karma-chrome-launcher": "^2.2.0", 45 | "karma-cli": "^1.0.1", 46 | "karma-mocha": "^1.3.0", 47 | "karma-mocha-reporter": "^2.2.5", 48 | "karma-webpack": "^3.0.0", 49 | "mocha": "^5.0.0", 50 | "sinon": "^13.0.0", 51 | "sinon-chai": "^3.0.0", 52 | "webpack": "^4.11.1" 53 | }, 54 | "dependencies": { 55 | "browser-process-hrtime": "^1.0.0", 56 | "co": "^4.6.0" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /test/bdd.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const sinon = require('sinon'); 4 | const chai = require('chai'); 5 | const sinonChai = require('sinon-chai'); 6 | 7 | chai.use(sinonChai); 8 | const expect = chai.expect; 9 | 10 | const timer = require('../index').timer; 11 | 12 | const FakeTick = function (diffToReturn) { 13 | this.getDiff = function () { 14 | return diffToReturn; 15 | }; 16 | }; 17 | 18 | const getTimerWithTicks = function (name, diffs) { 19 | const testTimer = timer(name); 20 | 21 | for (let i = 0, len = diffs.length; i < len; i++) { 22 | testTimer.ticks.push(new FakeTick(diffs[i])); 23 | } 24 | 25 | return testTimer; 26 | }; 27 | 28 | describe('BDD', function () { 29 | 30 | describe('Helpers', function () { 31 | describe('median', function () { 32 | 33 | it('should calculate the median correctly for a timer containing 1 tick', function () { 34 | const medianTestTimerWith1Ticks = getTimerWithTicks('medianTestTimerWith1Ticks', [1]); 35 | 36 | expect(medianTestTimerWith1Ticks.median()).to.equal(1); 37 | }); 38 | 39 | it('should calculate the median correctly for a timer containing 3 ticks', function () { 40 | const medianTestTimerWith3Ticks = getTimerWithTicks('medianTestTimerWith3Ticks', [1, 2, 3]); 41 | 42 | expect(medianTestTimerWith3Ticks.median()).to.equal(2); 43 | }); 44 | 45 | it('should calculate the median correctly for a timer containing 6 tick', function () { 46 | const medianTestTimerWith6Ticks = getTimerWithTicks('medianTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 47 | 48 | expect(medianTestTimerWith6Ticks.median()).to.equal(6.5); 49 | }); 50 | 51 | it('should calculate the median correctly for a timer containing 6 tick not ordered', function () { 52 | const medianTestTimerWith6Ticks = getTimerWithTicks('medianTestTimerWith6Ticks', [4, 1, 10, 9, 6, 7]); 53 | 54 | expect(medianTestTimerWith6Ticks.median()).to.equal(6.5); 55 | }); 56 | 57 | }); 58 | 59 | describe('mean', function () { 60 | 61 | it('should calculate the mean correctly for a timer containing 1 tick', function () { 62 | const meanTestTimerWith1Ticks = getTimerWithTicks('meanTestTimerWith1Ticks', [1]); 63 | 64 | expect(meanTestTimerWith1Ticks.mean()).to.equal(1); 65 | }); 66 | 67 | it('should calculate the mean correctly for a timer containing 3 ticks', function () { 68 | const meanTestTimerWith3Ticks = getTimerWithTicks('meanTestTimerWith3Ticks', [1, 2, 3]); 69 | 70 | expect(meanTestTimerWith3Ticks.mean()).to.equal(2); 71 | }); 72 | 73 | it('should calculate the mean correctly for a timer containing 6 tick', function () { 74 | const meanTestTimerWith6Ticks = getTimerWithTicks('meanTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 75 | 76 | expect(meanTestTimerWith6Ticks.mean()).to.equal(6.166666666666667); 77 | }); 78 | 79 | it('should calculate the mean correctly for a timer containing 6 tick not ordered', function () { 80 | const meanTestTimerWith6Ticks = getTimerWithTicks('meanTestTimerWith6Ticks', [4, 1, 10, 9, 6, 7]); 81 | 82 | expect(meanTestTimerWith6Ticks.mean()).to.equal(6.166666666666667); 83 | }); 84 | 85 | }); 86 | 87 | describe('duration', function () { 88 | 89 | it('should calculate the duration correctly for a timer containing 1 tick', function () { 90 | const durationTestTimerWith1Ticks = getTimerWithTicks('durationTestTimerWith1Ticks', [1]); 91 | 92 | expect(durationTestTimerWith1Ticks.duration()).to.equal(1); 93 | }); 94 | 95 | it('should calculate the duration correctly for a timer containing 3 ticks', function () { 96 | const durationTestTimerWith3Ticks = getTimerWithTicks('durationTestTimerWith3Ticks', [1, 2, 3]); 97 | 98 | expect(durationTestTimerWith3Ticks.duration()).to.equal(6); 99 | }); 100 | 101 | it('should calculate the duration correctly for a timer containing 6 tick', function () { 102 | const durationTestTimerWith6Ticks = getTimerWithTicks('durationTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 103 | 104 | expect(durationTestTimerWith6Ticks.duration()).to.equal(37); 105 | }); 106 | 107 | }); 108 | 109 | describe('min', function () { 110 | 111 | it('should calculate the min correctly for a timer containing 1 tick', function () { 112 | const minTestTimerWith1Ticks = getTimerWithTicks('minTestTimerWith1Ticks', [1]); 113 | 114 | expect(minTestTimerWith1Ticks.min()).to.equal(1); 115 | }); 116 | 117 | it('should calculate the min correctly for a timer containing 3 ticks', function () { 118 | const minTestTimerWith3Ticks = getTimerWithTicks('minTestTimerWith3Ticks', [1, 2, 3]); 119 | 120 | expect(minTestTimerWith3Ticks.min()).to.equal(1); 121 | }); 122 | 123 | it('should calculate the min correctly for a timer containing 6 tick', function () { 124 | const minTestTimerWith6Ticks = getTimerWithTicks('minTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 125 | 126 | expect(minTestTimerWith6Ticks.min()).to.equal(1); 127 | }); 128 | 129 | }); 130 | 131 | describe('max', function () { 132 | 133 | it('should calculate the max correctly for a timer containing 1 tick', function () { 134 | const maxTestTimerWith1Ticks = getTimerWithTicks('maxTestTimerWith1Ticks', [1]); 135 | 136 | expect(maxTestTimerWith1Ticks.max()).to.equal(1); 137 | }); 138 | 139 | it('should calculate the max correctly for a timer containing 3 ticks', function () { 140 | const maxTestTimerWith3Ticks = getTimerWithTicks('maxTestTimerWith3Ticks', [1, 2, 3]); 141 | 142 | expect(maxTestTimerWith3Ticks.max()).to.equal(3); 143 | }); 144 | 145 | it('should calculate the max correctly for a timer containing 6 tick', function () { 146 | const maxTestTimerWith6Ticks = getTimerWithTicks('maxTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 147 | 148 | expect(maxTestTimerWith6Ticks.max()).to.equal(10); 149 | }); 150 | 151 | }); 152 | 153 | describe('count', function () { 154 | 155 | it('should calculate the count correctly for a timer containing 1 tick', function () { 156 | const countTestTimerWith1Ticks = getTimerWithTicks('countTestTimerWith1Ticks', [1]); 157 | 158 | expect(countTestTimerWith1Ticks.count()).to.equal(1); 159 | }); 160 | 161 | it('should calculate the count correctly for a timer containing 3 ticks', function () { 162 | const countTestTimerWith3Ticks = getTimerWithTicks('countTestTimerWith3Ticks', [1, 2, 3]); 163 | 164 | expect(countTestTimerWith3Ticks.count()).to.equal(3); 165 | }); 166 | 167 | it('should calculate the count correctly for a timer containing 6 tick', function () { 168 | const countTestTimerWith6Ticks = getTimerWithTicks('countTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 169 | 170 | expect(countTestTimerWith6Ticks.count()).to.equal(6); 171 | }); 172 | 173 | }); 174 | 175 | describe('printResults', function () { 176 | it('should print the results nicely', function () { 177 | sinon.spy(console, 'log'); 178 | 179 | const medianTestTimerWith6Ticks = getTimerWithTicks('medianTestTimerWith6Ticks', [1, 4, 6, 7, 9, 10]); 180 | ['parse', 'duration', 'min', 'max', 'mean', 'median'] 181 | .forEach(method => sinon.spy(medianTestTimerWith6Ticks, method)); 182 | 183 | medianTestTimerWith6Ticks.printResults(); 184 | 185 | expect(console.log).to.have.callCount(5); 186 | expect(medianTestTimerWith6Ticks.parse).to.have.callCount(5); 187 | expect(medianTestTimerWith6Ticks.duration).to.have.callCount(2); 188 | ['min', 'max', 'mean', 'median'] 189 | .forEach(method => expect(medianTestTimerWith6Ticks[method]).to.have.callCount(1)); 190 | }); 191 | }); 192 | }); 193 | 194 | context('Generators', function () { 195 | var prom; 196 | const Tick = require('../index').Tick; 197 | 198 | beforeEach(function () { 199 | prom = ''; 200 | }); 201 | 202 | it('should resolve promises', function (done) { 203 | Tick.wrap('myOtherFunc', function* () { 204 | prom = yield Promise.resolve('foo'); 205 | 206 | expect(prom).to.equal('foo'); 207 | done(); 208 | }); 209 | }); 210 | 211 | it('should catch promises that do not succeed', function (done) { 212 | Tick.wrap('myOtherFunc', function* () { 213 | try { 214 | yield Promise.reject(new Error('foo')); 215 | } catch (e) { 216 | expect(e.message).to.equal('foo'); 217 | done(); 218 | } 219 | }); 220 | }); 221 | }); 222 | }); 223 | -------------------------------------------------------------------------------- /test/int.js: -------------------------------------------------------------------------------- 1 | const sinon = require('sinon'); 2 | const chai = require('chai'); 3 | const async = require('async'); 4 | 5 | const clock = sinon.useFakeTimers(); 6 | 7 | const exectimer = require('./../index'); 8 | const Tick = exectimer.Tick; 9 | 10 | const expect = chai.expect; 11 | 12 | const suts = { 13 | testCustomInit: function(n, cb) { 14 | const tick = new Tick('testCustomInit'); 15 | tick.start(); 16 | setTimeout(function () { 17 | tick.stop(); 18 | cb(); 19 | }, 100); 20 | }, 21 | testWrapFunction: function(n, cb) { 22 | Tick.wrap('testWrapFunction', (done) => { 23 | new Promise(function(resolve) { 24 | setTimeout(function () { 25 | resolve(); 26 | }, 100); 27 | }).then(() => { 28 | done(); 29 | cb(); 30 | }); 31 | }); 32 | }, 33 | testWrapGenerator: function(n, cb) { 34 | Tick.wrap('testWrapGenerator', function* () { 35 | yield new Promise(function(resolve) { 36 | setTimeout(function () { 37 | resolve(); 38 | cb(); 39 | }, 100); 40 | }); 41 | }); 42 | } 43 | }; 44 | 45 | describe('Integration - each 10 loops of 100ms timeouts', function () { 46 | 47 | Object.keys(suts).forEach(function(funcName) { 48 | describe(funcName, function() { 49 | before(function(done) { 50 | async.times(10, suts[funcName], function () { 51 | done(); 52 | }); 53 | clock.runAll(); 54 | }); 55 | 56 | it('mean should be between 100 ms', function () { 57 | expect(exectimer.timers[funcName].mean()).to.equal(100000000); 58 | }); 59 | 60 | it('median should be between 100', function () { 61 | expect(exectimer.timers[funcName].median()).to.equal(100000000); 62 | }); 63 | 64 | it('min should be between 100 and 106 ms', function () { 65 | expect(exectimer.timers[funcName].min()).to.equal(100000000); 66 | }); 67 | 68 | it('max should be between 100', function () { 69 | expect(exectimer.timers[funcName].max()).to.equal(100000000); 70 | }); 71 | 72 | it('count should be 10', function () { 73 | expect(exectimer.timers[funcName].count()).to.equal(10); 74 | }); 75 | }); 76 | }); 77 | 78 | describe('tick without stop method called', () => { 79 | const functionName = 'testTickWithoutStopCalled'; 80 | beforeEach(() => { 81 | const tick = new Tick(functionName); 82 | tick.start(); 83 | }); 84 | 85 | it('should not throw', () => { 86 | const sut = exectimer.timers[functionName].median.bind(exectimer.timers.testTickWithoutStopCalled); 87 | 88 | expect(sut).to.not.throw(); 89 | }); 90 | }); 91 | }); 92 | -------------------------------------------------------------------------------- /test/unit.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const chai = require('chai'); 4 | const expect = chai.expect; 5 | 6 | const t = require('./../index'); 7 | const Tick = t.Tick; 8 | 9 | describe('Unit', function () { 10 | describe('Timer', function () { 11 | 12 | const timer = t.timer; 13 | 14 | it('should return a timer object', function () { 15 | const newTimer = timer('mytimer'); 16 | 17 | expect(newTimer).to.be.an.instanceOf(Object); 18 | }); 19 | 20 | it('should have all needed helper functions', function () { 21 | const newTimer = timer('mytimer'); 22 | const helpers = ['median', 'mean', 'duration', 'min', 'max', 'count', 'parse']; 23 | 24 | expect(newTimer).to.be.an.instanceof(Object) 25 | .and.include.keys(helpers); 26 | 27 | helpers.forEach(function (helper) { 28 | expect(newTimer[helper]).to.be.a('function'); 29 | }); 30 | }); 31 | 32 | }); 33 | 34 | describe('Tick', function () { 35 | 36 | it('should have helper functions', function () { 37 | const tick = new Tick('mytick'); 38 | 39 | expect(tick.start).to.be.a('function'); 40 | expect(tick.stop).to.be.a('function'); 41 | expect(tick.getDiff).to.be.a('function'); 42 | }); 43 | 44 | it('should push a new item to the timers array', function () { 45 | const tick = new Tick('mytick'); 46 | 47 | tick.start(); 48 | tick.stop(); 49 | 50 | expect(t.timers.mytick).to.be.an.instanceOf(Object); 51 | }); 52 | 53 | context('wrapper', function () { 54 | 55 | it('should use function\'s name to add it to the timer array', function () { 56 | Tick.wrap(function myFunction(done) { 57 | done(); 58 | }); 59 | 60 | expect(t.timers.myFunction).to.be.an.instanceOf(Object); 61 | }); 62 | 63 | it('should use generator\'s name to add it to the timer array', function (cb) { 64 | Tick.wrap(function* myGenerator() { 65 | expect(t.timers.myGenerator).to.be.an.instanceOf(Object); 66 | cb(); 67 | }); 68 | }); 69 | 70 | it('should measure all calls', function () { 71 | 72 | function myNewFunction(done) { 73 | done(); 74 | } 75 | 76 | for (let i = 0; i < 10; i++) { 77 | Tick.wrap(myNewFunction); 78 | } 79 | 80 | expect(t.timers.myNewFunction.ticks).to.have.lengthOf(10); 81 | }); 82 | 83 | it('should name anonymous functions `anon`', function () { 84 | Tick.wrap(function (done) { 85 | done(); 86 | }); 87 | 88 | expect(t.timers.anon).to.be.instanceOf(Object); 89 | expect(t.timers.anon.ticks).to.have.a.lengthOf(1); 90 | }); 91 | 92 | it('should overwrite function\'s name if set as argument', function () { 93 | Tick.wrap('anotherFunc', function someFuncNameThatShouldBePicked(done) { 94 | done(); 95 | }); 96 | 97 | expect(t.timers.anotherFunc).to.be.instanceOf(Object); 98 | expect(t.timers.anotherFunc.ticks).to.have.a.lengthOf(1); 99 | 100 | expect(t.timers.someFuncNameThatShouldBePicked).to.be.an('undefined'); 101 | }); 102 | 103 | it('should throw if parameters are wrong', function () { 104 | expect(() => Tick.wrap('anotherFunc')).to.throw('Tick.wrap expects a callback function parameter'); 105 | }); 106 | }); 107 | 108 | }); 109 | 110 | }); 111 | --------------------------------------------------------------------------------