├── .editorconfig ├── .eslintrc.json ├── .gitattributes ├── .gitignore ├── .travis.yml ├── .verb.md ├── LICENSE ├── example.js ├── index.js ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | end_of_line = lf 7 | charset = utf-8 8 | indent_size = 2 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | insert_final_newline = false 15 | 16 | [**/{actual,fixtures,expected}/**] 17 | trim_trailing_whitespace = false 18 | insert_final_newline = false 19 | 20 | [**/templates/**] 21 | trim_trailing_whitespace = false 22 | insert_final_newline = false 23 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "ecmaFeatures": { 3 | "modules": true, 4 | "experimentalObjectRestSpread": true 5 | }, 6 | 7 | "env": { 8 | "browser": false, 9 | "es6": true, 10 | "node": true, 11 | "mocha": true 12 | }, 13 | 14 | "globals": { 15 | "document": false, 16 | "navigator": false, 17 | "window": false 18 | }, 19 | 20 | "rules": { 21 | "accessor-pairs": 2, 22 | "arrow-spacing": [2, { "before": true, "after": true }], 23 | "block-spacing": [2, "always"], 24 | "brace-style": [2, "1tbs", { "allowSingleLine": true }], 25 | "comma-dangle": [2, "never"], 26 | "comma-spacing": [2, { "before": false, "after": true }], 27 | "comma-style": [2, "last"], 28 | "constructor-super": 2, 29 | "curly": [2, "multi-line"], 30 | "dot-location": [2, "property"], 31 | "eol-last": 2, 32 | "eqeqeq": [2, "allow-null"], 33 | "generator-star-spacing": [2, { "before": true, "after": true }], 34 | "handle-callback-err": [2, "^(err|error)$" ], 35 | "indent": [2, 2, { "SwitchCase": 1 }], 36 | "key-spacing": [2, { "beforeColon": false, "afterColon": true }], 37 | "keyword-spacing": [2, { "before": true, "after": true }], 38 | "new-cap": [2, { "newIsCap": true, "capIsNew": false }], 39 | "new-parens": 2, 40 | "no-array-constructor": 2, 41 | "no-caller": 2, 42 | "no-class-assign": 2, 43 | "no-cond-assign": 2, 44 | "no-const-assign": 2, 45 | "no-control-regex": 2, 46 | "no-debugger": 2, 47 | "no-delete-var": 2, 48 | "no-dupe-args": 2, 49 | "no-dupe-class-members": 2, 50 | "no-dupe-keys": 2, 51 | "no-duplicate-case": 2, 52 | "no-empty-character-class": 2, 53 | "no-eval": 2, 54 | "no-ex-assign": 2, 55 | "no-extend-native": 2, 56 | "no-extra-bind": 2, 57 | "no-extra-boolean-cast": 2, 58 | "no-extra-parens": [2, "functions"], 59 | "no-fallthrough": 2, 60 | "no-floating-decimal": 2, 61 | "no-func-assign": 2, 62 | "no-implied-eval": 2, 63 | "no-inner-declarations": [2, "functions"], 64 | "no-invalid-regexp": 2, 65 | "no-irregular-whitespace": 2, 66 | "no-iterator": 2, 67 | "no-label-var": 2, 68 | "no-labels": 2, 69 | "no-lone-blocks": 2, 70 | "no-mixed-spaces-and-tabs": 2, 71 | "no-multi-spaces": 2, 72 | "no-multi-str": 2, 73 | "no-multiple-empty-lines": [2, { "max": 1 }], 74 | "no-native-reassign": 0, 75 | "no-negated-in-lhs": 2, 76 | "no-new": 2, 77 | "no-new-func": 2, 78 | "no-new-object": 2, 79 | "no-new-require": 2, 80 | "no-new-wrappers": 2, 81 | "no-obj-calls": 2, 82 | "no-octal": 2, 83 | "no-octal-escape": 2, 84 | "no-proto": 0, 85 | "no-redeclare": 2, 86 | "no-regex-spaces": 2, 87 | "no-return-assign": 2, 88 | "no-self-compare": 2, 89 | "no-sequences": 2, 90 | "no-shadow-restricted-names": 2, 91 | "no-spaced-func": 2, 92 | "no-sparse-arrays": 2, 93 | "no-this-before-super": 2, 94 | "no-throw-literal": 2, 95 | "no-trailing-spaces": 0, 96 | "no-undef": 2, 97 | "no-undef-init": 2, 98 | "no-unexpected-multiline": 2, 99 | "no-unneeded-ternary": [2, { "defaultAssignment": false }], 100 | "no-unreachable": 2, 101 | "no-unused-vars": [2, { "vars": "all", "args": "none" }], 102 | "no-useless-call": 0, 103 | "no-with": 2, 104 | "one-var": [0, { "initialized": "never" }], 105 | "operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }], 106 | "padded-blocks": [0, "never"], 107 | "quotes": [2, "single", "avoid-escape"], 108 | "radix": 2, 109 | "semi": [2, "always"], 110 | "semi-spacing": [2, { "before": false, "after": true }], 111 | "space-before-blocks": [2, "always"], 112 | "space-before-function-paren": [2, "never"], 113 | "space-in-parens": [2, "never"], 114 | "space-infix-ops": 2, 115 | "space-unary-ops": [2, { "words": true, "nonwords": false }], 116 | "spaced-comment": [0, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], 117 | "use-isnan": 2, 118 | "valid-typeof": 2, 119 | "wrap-iife": [2, "any"], 120 | "yoda": [2, "never"] 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Enforce Unix newlines 2 | * text eol=lf 3 | 4 | # binaries 5 | *.ai binary 6 | *.psd binary 7 | *.jpg binary 8 | *.gif binary 9 | *.png binary 10 | *.jpeg binary 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | *.sublime-* 3 | _gh_pages 4 | bower_components 5 | node_modules 6 | npm-debug.log 7 | actual 8 | test/actual 9 | temp 10 | tmp 11 | TODO.md 12 | vendor 13 | .idea 14 | benchmark 15 | coverage 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - stable 5 | - '5' 6 | - '4' 7 | - '0.12' 8 | - '0.10' 9 | matrix: 10 | fast_finish: true 11 | allow_failures: 12 | - node_js: '0.10' 13 | - node_js: '0.12' 14 | -------------------------------------------------------------------------------- /.verb.md: -------------------------------------------------------------------------------- 1 | ## Usage 2 | 3 | Uses [pretty-time][] to format time diffs. 4 | 5 | ```js 6 | var Time = require('{%= name %}'); 7 | var time = new Time(); 8 | 9 | // create a start time for `foo` 10 | time.start('foo'); 11 | 12 | // call `end` wherever the `foo` process ends 13 | console.log(time.end('foo')); 14 | //=> 12ms 15 | ``` 16 | 17 | ## API 18 | {%= apidocs('index.js') %} 19 | 20 | ## Options 21 | 22 | ### options.logDiff 23 | 24 | Disable time diffs, or filter time diffs to the specified name(s). 25 | 26 | **type**: `Boolean|String` 27 | 28 | **default**: `undefined` 29 | 30 | 31 | ### options.nocolor 32 | 33 | Set to `true` to disable color in the output. 34 | 35 | **type**: `Boolean` 36 | 37 | **default**: `undefined` 38 | 39 | **Example** 40 | 41 | ```js 42 | var diff = time.diff('foo', {nocolor: true}); 43 | ``` 44 | 45 | ### options.formatArgs 46 | 47 | Format arguments passed to `process.stderr`. 48 | 49 | **type**: `Function` 50 | 51 | **default**: `undefined` 52 | 53 | **Examples** 54 | 55 | Show `message` and `elapsed` time only: 56 | 57 | ```js 58 | var time = new Time(); 59 | var diff = time.diff('foo', { 60 | formatArgs: function(timestamp, name, msg, elapsed) { 61 | return [msg, elapsed]; 62 | } 63 | }); 64 | 65 | diff('first diff'); 66 | //=> 'first diff 36μs' 67 | diff('second diff'); 68 | //=> 'second diff 71μs' 69 | ``` 70 | 71 | Show `name` and `elapsed` time only: 72 | 73 | ```js 74 | var diff = time.diff('foo', { 75 | formatArgs: function(timestamp, name, msg, elapsed) { 76 | return [name, elapsed]; 77 | } 78 | }); 79 | 80 | diff('first diff'); 81 | //=> 'foo 36μs' 82 | diff('second diff'); 83 | //=> 'foo 71μs' 84 | ``` 85 | 86 | ## Examples 87 | 88 | Create an instance of `Time`, optionally specifying the time scale to use and the number of decimal places to display. 89 | 90 | **Options** 91 | 92 | - `options.smallest`: the smallest time scale to show 93 | - `options.digits`: the number of decimal places to display (`digits`) 94 | 95 | **Examples** 96 | 97 | _(See [pretty-time][] for all available formats)_ 98 | 99 | Given the following: 100 | 101 | ```js 102 | var time = new Time(options); 103 | time.start('foo'); 104 | ``` 105 | 106 | Returns milliseconds by default 107 | 108 | ```js 109 | console.log(time.end('foo')); 110 | //=> 13ms 111 | ``` 112 | 113 | Milliseconds to 3 decimal places 114 | 115 | ```js 116 | console.log(time.end('foo', 'ms', 3)); 117 | // or 118 | console.log(time.end('foo', 3)); 119 | //=> 12.743ms 120 | ``` 121 | 122 | Seconds to 3 decimal places 123 | 124 | ```js 125 | console.log(time.end('foo', 's', 3)); 126 | //=> 0.013s 127 | ``` 128 | 129 | Seconds 130 | 131 | ```js 132 | console.log(time.end('foo', 's')); 133 | //=> 0s 134 | ``` 135 | 136 | Microseconds 137 | 138 | ```js 139 | console.log(time.end('foo', 'μs')); 140 | //=> 12ms 934μs 141 | ``` 142 | 143 | Microseconds to 2 decimal places 144 | 145 | ```js 146 | console.log(time.end('foo', 'μs', 2)); 147 | //=> 14ms 435.78μs 148 | ``` 149 | 150 | nano-seconds 151 | 152 | ```js 153 | console.log(time.end('foo', 'n', 3)); 154 | //=> 13ms 796μs 677ns 155 | ``` 156 | 157 | nano-seconds to 3 decimal places 158 | 159 | ```js 160 | console.log(time.end('foo', 'n', 3)); 161 | //=> 13ms 427μs 633.000ns 162 | ``` 163 | 164 | ## CLI usage 165 | 166 | If you're using `time-diff` with a command line application, try using [minimist][] for setting options. 167 | 168 | ```js 169 | var opts = {alias: {nocolor: 'n', logTime: 't', logDiff: 'd'}}; 170 | var argv = require('minimist')(process.argv.slice(2), opts); 171 | 172 | var Time = require('time-diff'); 173 | var time = new Time(argv); 174 | ``` 175 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015-2016, Jon Schlinkert. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var opts = {alias: {logDiff: 'd', logTime: 't'}, boolean: ['logDiff']}; 4 | var argv = require('minimist')(process.argv.slice(2), opts); 5 | var Time = require('./'); 6 | console.log(argv) 7 | 8 | var time = new Time(argv); 9 | time.start('foo'); 10 | console.log(time.end('foo', 's')); 11 | console.log(time.end('foo', 's', 3)); 12 | console.log(time.end('foo', 'ms', 3)); 13 | console.log(time.end('foo', 'μs')); 14 | console.log(time.end('foo', 'μs', 2)); 15 | console.log(time.end('foo', 'n', 3)); 16 | console.log(time.end('foo', 'n')); 17 | console.log(time.end('foo', 3)); 18 | console.log(time.end('foo')); 19 | 20 | // time = new Time('s', 6); 21 | // time.start('bar'); 22 | // time.start('baz'); 23 | // console.log(time.end('bar')); 24 | // console.log(time.end('baz')); 25 | 26 | /** 27 | * Diffs 28 | * 29 | * Pass an instance of `time-diff` to `log-time-diff`, 30 | * along with a "namespace" to use for diffs 31 | */ 32 | 33 | time.options.formatArgs = function(timestamp, name, msg, elapsed) { 34 | return [timestamp, msg, elapsed]; 35 | }; 36 | 37 | var diffAbc = time.diff('abc', argv); 38 | var diffXyz = time.diff('xyz', argv); 39 | 40 | /** 41 | * Next, 42 | */ 43 | 44 | // do stuff 45 | diffAbc('after init'); 46 | 47 | // do more stuff... 48 | diffAbc('before options'); 49 | 50 | // then load some options 51 | diffAbc('after options'); 52 | 53 | 54 | /** 55 | * Next, 56 | */ 57 | 58 | // do stuff 59 | diffXyz('after init'); 60 | 61 | // do more stuff... 62 | diffXyz('before options'); 63 | 64 | // then load some options 65 | diffXyz('after options'); 66 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * log-time 3 | * 4 | * Copyright (c) 2015, Jon Schlinkert. 5 | * Licensed under the MIT License. 6 | */ 7 | 8 | 'use strict'; 9 | 10 | var extend = require('extend-shallow'); 11 | var isNumber = require('is-number'); 12 | var pretty = require('pretty-time'); 13 | var log = require('log-utils'); 14 | 15 | /** 16 | * Create an instance of `Time`, optionally specifying the 17 | * time-scale to use and/or the number of decimal places to display. 18 | * 19 | * ```js 20 | * var time = new Time('s', 3); 21 | * ``` 22 | * @param {String|Number} `smallest` The smallest time scale to show, or the number of decimal places to display 23 | * @param {Number} `digits` The number of decimal places to display 24 | */ 25 | 26 | function Time(options) { 27 | if (!(this instanceof Time)) { 28 | return new Time(options); 29 | } 30 | 31 | this.options = options || {}; 32 | var smallest = this.options.smallest; 33 | var digits = this.options.digits; 34 | 35 | if (isNumber(smallest)) { 36 | digits = smallest; 37 | smallest = null; 38 | } 39 | 40 | this.smallest = smallest; 41 | this.digits = digits; 42 | this.times = {}; 43 | } 44 | 45 | /** 46 | * Start a timer for the given `name`. 47 | * 48 | * ```js 49 | * var time = new Time(); 50 | * time.start('foo'); 51 | * ``` 52 | * @param {String} `name` Name to use for the starting time. 53 | * @return {Array} Returns the array from `process.hrtime()` 54 | * @api public 55 | */ 56 | 57 | Time.prototype.start = function(name) { 58 | return (this.times[name] = process.hrtime()); 59 | }; 60 | 61 | /** 62 | * Returns the cumulative elapsed time since the **first time** `time.start(name)` 63 | * was called. 64 | * 65 | * ```js 66 | * var time = new Time(); 67 | * time.start('foo'); 68 | * 69 | * // do stuff 70 | * time.end('foo'); 71 | * //=> 104μs 72 | * 73 | * // do more stuff 74 | * time.end('foo'); 75 | * //=> 1ms 76 | * 77 | * // do more stuff 78 | * time.end('foo'); 79 | * //=> 2ms 80 | * ``` 81 | * @param {String} `name` The name of the cached starting time to create the diff 82 | * @return {Array} Returns the array from `process.hrtime()` 83 | * @api public 84 | */ 85 | 86 | Time.prototype.end = function(name, smallest, digits) { 87 | var start = this.times[name]; 88 | if (typeof start === 'undefined') { 89 | throw new Error(log.colors.red('start time not defined for "' + name + '"')); 90 | } 91 | 92 | if (isNumber(smallest)) { 93 | digits = smallest; 94 | smallest = null; 95 | } 96 | 97 | if (!smallest && this.smallest) smallest = this.smallest; 98 | if (!digits && this.digits) digits = this.digits; 99 | return pretty(process.hrtime(start), smallest, digits); 100 | }; 101 | 102 | /** 103 | * Returns a function for logging out out both the cumulative elapsed time since 104 | * the first time `.diff(name)` was called, as well as the incremental elapsed 105 | * time since the last `.diff(name)` was called. Unlike `.end()`, this method logs 106 | * to `stderr` instead of returning a string. We could probably change this to 107 | * return an object, feedback welcome. 108 | * 109 | * ```js 110 | * var time = new Time(); 111 | * var diff = time.diff('my-app-name'); 112 | * 113 | * // do stuff 114 | * diff('after init'); 115 | * //=> [19:44:05] my-app-name: after init 108μs 116 | * 117 | * // do more stuff 118 | * diff('before options'); 119 | * //=> [19:44:05] my-app-name: before options 2ms (+2ms) 120 | * 121 | * // do more stuff 122 | * diff('after options'); 123 | * //=> [19:44:05] my-app-name: after options 2ms (+152μs) 124 | * ``` 125 | * Results in something like: 126 | *
127 | * screen shot 2016-04-13 at 7 45 12 pm 128 | * 129 | * @param {String} `name` The name of the starting time to store. 130 | * @param {String} `options` 131 | * @api public 132 | */ 133 | 134 | Time.prototype.diff = function(namespace, options) { 135 | var opts = {}; 136 | extend(opts, this.options, options); 137 | 138 | this.start(namespace); 139 | var time = this; 140 | var prev; 141 | 142 | function diff(msg) { 143 | if (typeof opts.logTimeDiffs !== 'undefined') { 144 | opts.logDiff = opts.logTimeDiffs; 145 | } 146 | 147 | if (typeof opts.logDiff === 'string') { 148 | if (!toRegex(opts.logDiff).test(namespace)) { 149 | // garbage collect 150 | time.times[namespace] = null; 151 | return; 152 | } 153 | } 154 | if (opts.logDiff === false) { 155 | // garbage collect 156 | time.times[namespace] = null; 157 | return; 158 | } 159 | 160 | var timestamp = log.timestamp; 161 | var magenta = log.colors.magenta; 162 | var gray = log.colors.gray; 163 | var name = opts.prefix === false ? '' : namespace; 164 | 165 | if (typeof opts.diffColor === 'function') { 166 | gray = opts.diffColor; 167 | } 168 | 169 | if (opts.nocolor === true) { 170 | magenta = identity; 171 | gray = identity; 172 | } 173 | 174 | if (opts.timestamp === false) { 175 | timestamp = ''; 176 | } 177 | 178 | var elapsed = magenta(time.end(namespace)); 179 | var val; 180 | 181 | if (typeof prev !== 'undefined') { 182 | val = time.end(prev); 183 | } 184 | 185 | // start the next cycle 186 | time.start(msg); 187 | prev = msg; 188 | 189 | if (typeof val === 'string') { 190 | elapsed += gray(' (+' + val + ')'); 191 | } 192 | 193 | // create the arguments to log out 194 | var args = [timestamp, name, msg, elapsed].filter(Boolean); 195 | 196 | // support custom `.format` function 197 | if (typeof opts.formatArgs === 'function') { 198 | args = [].concat(opts.formatArgs.apply(null, args) || []); 199 | } 200 | 201 | console.error.apply(console, args); 202 | }; 203 | 204 | return diff; 205 | }; 206 | 207 | function toRegex(str) { 208 | if (~str.indexOf(',')) { 209 | str = '(' + str.split(',').join('|') + ')'; 210 | } 211 | str = str.replace(/\*/g, '[^.]*?'); 212 | return new RegExp('^' + str + '$'); 213 | } 214 | 215 | function identity(val) { 216 | return val; 217 | } 218 | 219 | /** 220 | * Expose `time` 221 | */ 222 | 223 | module.exports = Time; 224 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "time-diff", 3 | "description": "Returns the formatted, high-resolution time difference between `start` and `end` times.", 4 | "version": "0.3.1", 5 | "homepage": "https://github.com/jonschlinkert/time-diff", 6 | "author": "Jon Schlinkert (https://github.com/jonschlinkert)", 7 | "repository": "jonschlinkert/time-diff", 8 | "bugs": { 9 | "url": "https://github.com/jonschlinkert/time-diff/issues" 10 | }, 11 | "license": "MIT", 12 | "files": [ 13 | "index.js" 14 | ], 15 | "main": "index.js", 16 | "engines": { 17 | "node": ">=0.10.0" 18 | }, 19 | "scripts": { 20 | "test": "mocha" 21 | }, 22 | "dependencies": { 23 | "extend-shallow": "^2.0.1", 24 | "is-number": "^2.1.0", 25 | "log-utils": "^0.1.0", 26 | "pretty-time": "^0.2.0" 27 | }, 28 | "devDependencies": { 29 | "gulp-format-md": "^0.1.7", 30 | "minimist": "^1.2.0", 31 | "mocha": "^2.4.5", 32 | "strip-color": "^0.1.0" 33 | }, 34 | "keywords": [ 35 | "console", 36 | "diff", 37 | "difference", 38 | "elapse", 39 | "elapsed", 40 | "log", 41 | "pretty", 42 | "terminal", 43 | "time", 44 | "time-diff", 45 | "timer" 46 | ], 47 | "verb": { 48 | "plugins": [ 49 | "gulp-format-md" 50 | ], 51 | "reflinks": [ 52 | "pretty-time", 53 | "verb", 54 | "minimist" 55 | ], 56 | "related": { 57 | "list": [ 58 | "ansi-colors", 59 | "log-utils", 60 | "pretty-time", 61 | "time-diff" 62 | ] 63 | }, 64 | "layout": "default", 65 | "toc": { 66 | "render": false 67 | }, 68 | "run": true, 69 | "lint": { 70 | "reflinks": true 71 | }, 72 | "tasks": [ 73 | "readme" 74 | ] 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # time-diff [![NPM version](https://img.shields.io/npm/v/time-diff.svg?style=flat)](https://www.npmjs.com/package/time-diff) [![NPM downloads](https://img.shields.io/npm/dm/time-diff.svg?style=flat)](https://npmjs.org/package/time-diff) [![Build Status](https://img.shields.io/travis/jonschlinkert/time-diff.svg?style=flat)](https://travis-ci.org/jonschlinkert/time-diff) 2 | 3 | Returns the formatted, high-resolution time difference between `start` and `end` times. 4 | 5 | ## Install 6 | 7 | Install with [npm](https://www.npmjs.com/): 8 | 9 | ```sh 10 | $ npm install time-diff --save 11 | ``` 12 | 13 | ## Usage 14 | 15 | Uses [pretty-time][] to format time diffs. 16 | 17 | ```js 18 | var Time = require('time-diff'); 19 | var time = new Time(); 20 | 21 | // create a start time for `foo` 22 | time.start('foo'); 23 | 24 | // call `end` wherever the `foo` process ends 25 | console.log(time.end('foo')); 26 | //=> 12ms 27 | ``` 28 | 29 | ## API 30 | 31 | ### [.start](index.js#L57) 32 | 33 | Start a timer for the given `name`. 34 | 35 | **Params** 36 | 37 | * `name` **{String}**: Name to use for the starting time. 38 | * `returns` **{Array}**: Returns the array from `process.hrtime()` 39 | 40 | **Example** 41 | 42 | ```js 43 | var time = new Time(); 44 | time.start('foo'); 45 | ``` 46 | 47 | ### [.end](index.js#L86) 48 | 49 | Returns the cumulative elapsed time since the **first time** `time.start(name)` was called. 50 | 51 | **Params** 52 | 53 | * `name` **{String}**: The name of the cached starting time to create the diff 54 | * `returns` **{Array}**: Returns the array from `process.hrtime()` 55 | 56 | **Example** 57 | 58 | ```js 59 | var time = new Time(); 60 | time.start('foo'); 61 | 62 | // do stuff 63 | time.end('foo'); 64 | //=> 104μs 65 | 66 | // do more stuff 67 | time.end('foo'); 68 | //=> 1ms 69 | 70 | // do more stuff 71 | time.end('foo'); 72 | //=> 2ms 73 | ``` 74 | 75 | ### [.diff](index.js#L134) 76 | 77 | Returns a function for logging out out both the cumulative elapsed time since the first time `.diff(name)` was called, as well as the incremental elapsed time since the last `.diff(name)` was called. Unlike `.end()`, this method logs to `stderr` instead of returning a string. We could probably change this to return an object, feedback welcome. 78 | 79 | Results in something like: 80 |
81 | screen shot 2016-04-13 at 7 45 12 pm 82 | 83 | **Params** 84 | 85 | * `name` **{String}**: The name of the starting time to store. 86 | * `options` **{String}** 87 | 88 | **Example** 89 | 90 | ```js 91 | var time = new Time(); 92 | var diff = time.diff('my-app-name'); 93 | 94 | // do stuff 95 | diff('after init'); 96 | //=> [19:44:05] my-app-name: after init 108μs 97 | 98 | // do more stuff 99 | diff('before options'); 100 | //=> [19:44:05] my-app-name: before options 2ms (+2ms) 101 | 102 | // do more stuff 103 | diff('after options'); 104 | //=> [19:44:05] my-app-name: after options 2ms (+152μs) 105 | ``` 106 | 107 | ## Options 108 | 109 | ### options.logDiff 110 | 111 | Disable time diffs, or filter time diffs to the specified name(s). 112 | 113 | **type**: `Boolean|String` 114 | 115 | **default**: `undefined` 116 | 117 | ### options.nocolor 118 | 119 | Set to `true` to disable color in the output. 120 | 121 | **type**: `Boolean` 122 | 123 | **default**: `undefined` 124 | 125 | **Example** 126 | 127 | ```js 128 | var diff = time.diff('foo', {nocolor: true}); 129 | ``` 130 | 131 | ### options.formatArgs 132 | 133 | Format arguments passed to `process.stderr`. 134 | 135 | **type**: `Function` 136 | 137 | **default**: `undefined` 138 | 139 | **Examples** 140 | 141 | Show `message` and `elapsed` time only: 142 | 143 | ```js 144 | var time = new Time(); 145 | var diff = time.diff('foo', { 146 | formatArgs: function(timestamp, name, msg, elapsed) { 147 | return [msg, elapsed]; 148 | } 149 | }); 150 | 151 | diff('first diff'); 152 | //=> 'first diff 36μs' 153 | diff('second diff'); 154 | //=> 'second diff 71μs' 155 | ``` 156 | 157 | Show `name` and `elapsed` time only: 158 | 159 | ```js 160 | var diff = time.diff('foo', { 161 | formatArgs: function(timestamp, name, msg, elapsed) { 162 | return [name, elapsed]; 163 | } 164 | }); 165 | 166 | diff('first diff'); 167 | //=> 'foo 36μs' 168 | diff('second diff'); 169 | //=> 'foo 71μs' 170 | ``` 171 | 172 | ## Examples 173 | 174 | Create an instance of `Time`, optionally specifying the time scale to use and the number of decimal places to display. 175 | 176 | **Options** 177 | 178 | * `options.smallest`: the smallest time scale to show 179 | * `options.digits`: the number of decimal places to display (`digits`) 180 | 181 | **Examples** 182 | 183 | _(See [pretty-time][] for all available formats)_ 184 | 185 | Given the following: 186 | 187 | ```js 188 | var time = new Time(options); 189 | time.start('foo'); 190 | ``` 191 | 192 | Returns milliseconds by default 193 | 194 | ```js 195 | console.log(time.end('foo')); 196 | //=> 13ms 197 | ``` 198 | 199 | Milliseconds to 3 decimal places 200 | 201 | ```js 202 | console.log(time.end('foo', 'ms', 3)); 203 | // or 204 | console.log(time.end('foo', 3)); 205 | //=> 12.743ms 206 | ``` 207 | 208 | Seconds to 3 decimal places 209 | 210 | ```js 211 | console.log(time.end('foo', 's', 3)); 212 | //=> 0.013s 213 | ``` 214 | 215 | Seconds 216 | 217 | ```js 218 | console.log(time.end('foo', 's')); 219 | //=> 0s 220 | ``` 221 | 222 | Microseconds 223 | 224 | ```js 225 | console.log(time.end('foo', 'μs')); 226 | //=> 12ms 934μs 227 | ``` 228 | 229 | Microseconds to 2 decimal places 230 | 231 | ```js 232 | console.log(time.end('foo', 'μs', 2)); 233 | //=> 14ms 435.78μs 234 | ``` 235 | 236 | nano-seconds 237 | 238 | ```js 239 | console.log(time.end('foo', 'n', 3)); 240 | //=> 13ms 796μs 677ns 241 | ``` 242 | 243 | nano-seconds to 3 decimal places 244 | 245 | ```js 246 | console.log(time.end('foo', 'n', 3)); 247 | //=> 13ms 427μs 633.000ns 248 | ``` 249 | 250 | ## CLI usage 251 | 252 | If you're using `time-diff` with a command line application, try using [minimist][] for setting options. 253 | 254 | ```js 255 | var opts = {alias: {nocolor: 'n', logTime: 't', logDiff: 'd'}}; 256 | var argv = require('minimist')(process.argv.slice(2), opts); 257 | 258 | var Time = require('time-diff'); 259 | var time = new Time(argv); 260 | ``` 261 | 262 | ## Related projects 263 | 264 | You might also be interested in these projects: 265 | 266 | * [ansi-colors](https://www.npmjs.com/package/ansi-colors): Collection of ansi colors and styles. | [homepage](https://github.com/doowb/ansi-colors) 267 | * [log-utils](https://www.npmjs.com/package/log-utils): Basic logging utils: colors, symbols and timestamp. | [homepage](https://github.com/jonschlinkert/log-utils) 268 | * [pretty-time](https://www.npmjs.com/package/pretty-time): Easily format the time from node.js `process.hrtime`. Works with timescales ranging from weeks to nanoseconds. | [homepage](https://github.com/jonschlinkert/pretty-time) 269 | * [time-diff](https://www.npmjs.com/package/time-diff): Returns the formatted, high-resolution time difference between `start` and `end` times. | [homepage](https://github.com/jonschlinkert/time-diff) 270 | 271 | ## Contributing 272 | 273 | Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/time-diff/issues/new). 274 | 275 | ## Building docs 276 | 277 | Generate readme and API documentation with [verb][]: 278 | 279 | ```sh 280 | $ npm install verb && npm run docs 281 | ``` 282 | 283 | Or, if [verb][] is installed globally: 284 | 285 | ```sh 286 | $ verb 287 | ``` 288 | 289 | ## Running tests 290 | 291 | Install dev dependencies: 292 | 293 | ```sh 294 | $ npm install -d && npm test 295 | ``` 296 | 297 | ## Author 298 | 299 | **Jon Schlinkert** 300 | 301 | * [github/jonschlinkert](https://github.com/jonschlinkert) 302 | * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) 303 | 304 | ## License 305 | 306 | Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). 307 | Released under the [MIT license](https://github.com/jonschlinkert/time-diff/blob/master/LICENSE). 308 | 309 | *** 310 | 311 | _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 30, 2016._ 312 | 313 | [pretty-time](https://github.com/jonschlinkert/pretty-time) 314 | [minimist](https://github.com/substack/minimist) 315 | [verb](https://github.com/verbose/verb) -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | require('mocha'); 4 | var assert = require('assert'); 5 | var strip = require('strip-color'); 6 | var Time = require('./'); 7 | var time; 8 | 9 | describe('time', function() { 10 | beforeEach(function() { 11 | time = new Time(); 12 | }); 13 | 14 | describe('API', function() { 15 | it('should expose a "start" method', function() { 16 | assert.equal(typeof time.start, 'function'); 17 | }); 18 | it('should expose an "end" method', function() { 19 | assert.equal(typeof time.end, 'function'); 20 | }); 21 | it('should expose a "times" object', function() { 22 | assert.equal(typeof time.times, 'object'); 23 | }); 24 | }); 25 | 26 | describe('.start', function() { 27 | it('should cache process.hrtime() start times', function() { 28 | time.start('a'); 29 | time.start('b'); 30 | time.start('c'); 31 | assert(Array.isArray(time.times.a)); 32 | assert(Array.isArray(time.times.b)); 33 | assert(Array.isArray(time.times.c)); 34 | }); 35 | 36 | it('should return calculated time as a string', function() { 37 | time.start('a'); 38 | assert.equal(typeof time.end('a'), 'string'); 39 | }); 40 | 41 | it('should throw an error when start time is not defined', function(cb) { 42 | try { 43 | time.end('foo'); 44 | cb(new Error('expected an error')); 45 | } catch (err) { 46 | assert(err); 47 | assert(/start time/.test(err.message)); 48 | cb(); 49 | } 50 | }); 51 | }); 52 | 53 | describe('.diff', function() { 54 | it('should expose a .diff method', function() { 55 | assert.equal(typeof time.diff, 'function'); 56 | }); 57 | 58 | it('should NOT log times when `options.logDiff` is false', function() { 59 | var time = new Time(); 60 | var error = console.error; 61 | var count = 0; 62 | 63 | console.error = function(timestamp, name, msg, elapsed) { 64 | count++; 65 | }; 66 | 67 | var diff = time.diff('generator', {logDiff: false}); 68 | diff('one'); 69 | diff('two'); 70 | diff('three'); 71 | assert.equal(count, 0); 72 | }); 73 | 74 | it('should log times when `options.logTimes` IS true', function() { 75 | var time = new Time(); 76 | var error = console.error; 77 | var count = 0; 78 | 79 | console.error = function(timestamp, name, msg, elapsed) { 80 | count++; 81 | }; 82 | 83 | var diff = time.diff('generator', {logTimes: true}); 84 | diff('one'); 85 | diff('two'); 86 | diff('three'); 87 | assert.equal(count, 3); 88 | }); 89 | 90 | it('should only log times that match the value passed on `options.times`', function() { 91 | var time = new Time(); 92 | var error = console.error; 93 | var count = 0; 94 | 95 | console.error = function(timestamp, name, msg, elapsed) { 96 | count++; 97 | }; 98 | 99 | var name = 'one'; 100 | 101 | var one = time.diff('one', {logDiff: name}); 102 | var two = time.diff('two', {logDiff: name}); 103 | 104 | one('foo'); 105 | one('bar'); 106 | one('baz'); 107 | 108 | two('foo'); 109 | two('bar'); 110 | two('baz'); 111 | 112 | assert.equal(count, 3); 113 | }); 114 | 115 | it('should log colors when `options.nocolor` is NOT true', function() { 116 | var time = new Time(); 117 | var error = console.error; 118 | var count = 0; 119 | 120 | console.error = function(timestamp, name, msg, elapsed) { 121 | assert.notEqual(elapsed, strip(elapsed)); 122 | count++; 123 | }; 124 | 125 | var diff = time.diff('generator', {times: true}); 126 | diff('one'); 127 | diff('two'); 128 | diff('three'); 129 | assert.equal(count, 3); 130 | }); 131 | 132 | it('should NOT log colors when `options.nocolor` is true', function() { 133 | var time = new Time(); 134 | var error = console.error; 135 | var count = 0; 136 | 137 | console.error = function(timestamp, name, msg, elapsed) { 138 | assert.equal(elapsed, strip(elapsed)); 139 | count++; 140 | }; 141 | 142 | var diff = time.diff('generator', {nocolor: true}); 143 | diff('one'); 144 | diff('two'); 145 | diff('three'); 146 | assert.equal(count, 3); 147 | }); 148 | 149 | it('should support a custom `formatArgs` function', function() { 150 | var time = new Time(); 151 | var error = console.error; 152 | var count = 0; 153 | 154 | console.error = function(timestamp, name, msg, elapsed) { 155 | if (count === 0) assert.equal(timestamp, 'one'); 156 | if (count === 1) assert.equal(timestamp, 'two'); 157 | if (count === 2) assert.equal(timestamp, 'three'); 158 | count++; 159 | }; 160 | 161 | var diff = time.diff('generator', { 162 | formatArgs: function(timestamp, name, msg) { 163 | return msg; 164 | } 165 | }); 166 | 167 | diff('one'); 168 | diff('two'); 169 | diff('three'); 170 | assert.equal(count, 3); 171 | }); 172 | }); 173 | }); 174 | 175 | 176 | --------------------------------------------------------------------------------