Skip to content

Commit d741d7e

Browse files
committed
Allowing measurement of multiple time slots
Changed implementation of measureStart and measureStop, added measurePause function, using an array to store measured time slots bug fixed when measureStart called multiple times error in measurePause when label undefined
1 parent f27c0e8 commit d741d7e

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

README.md

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,13 @@ myTimer.getDuration() // 18000
160160

161161
#### `.measureStart(label)`
162162

163-
Start a high-performance measurement with an associated label, you need to use
163+
Start or continue a high-performance measurement with the associated label, you need to use
164164
the same label to stop measurement, so make sure you've saved it
165165

166+
#### `.measurePause(label)`
167+
168+
Pause the measurement with the associated label
169+
166170
#### `.measureStop(label)`
167171

168172
Stop the measument with the associated label, returns the number of elapsed ms
@@ -171,12 +175,23 @@ Example:
171175

172176
```javascript
173177

174-
myTimer.measureStart('label1');
178+
var label = 'label1';
179+
180+
myTimer.measureStart(label);
175181
var a = [];
176182
for (var i = 10000000; i >= 0; i--) {
177183
a.push(i * Math.random());
178184
};
179-
myTimer.measureStop('label1'); // 276 i.e.
185+
myTimer.measurePause(label);
186+
187+
// do something else
188+
189+
myTimer.measureStart(label);
190+
for (var i = 0, sum = 0; i < a.length; i++) {
191+
sum += a[i];
192+
};
193+
var time_elapsed = myTimer.measureStop(label);
194+
180195
```
181196

182197
> Note!

src/timer.js

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,38 @@
105105
}
106106

107107
Timer.prototype.measureStart = function (label) {
108-
this._.measures[label || ''] = +new Date
108+
109+
if (!this._.measures[label || '']) this._.measures[label || ''] = []
110+
111+
this._.measures[label || '']._ = {
112+
startTime: +new Date,
113+
paused: false
114+
}
115+
return this
116+
}
117+
118+
Timer.prototype.measurePause = function (label) {
119+
var measureArr = this._.measures[label || '']
120+
if (measureArr && !measureArr._.paused) {
121+
measureArr.push(+new Date - measureArr._.startTime)
122+
measureArr._.paused = true
123+
}
109124
return this
110125
}
111126

112127
Timer.prototype.measureStop = function (label) {
113-
return +new Date - this._.measures[label || '']
128+
this.measurePause(label)
129+
var arr = this._.measures[label || ''],
130+
result = 0
131+
if (!arr) return result
132+
133+
var len = arr.length
134+
for (var i = 0; i < len; ++i)
135+
result += arr[i]
136+
137+
delete this._.measures[label || '']
138+
139+
return result
114140
}
115141

116142
function end () {

0 commit comments

Comments
 (0)