function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements || []; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = null; currentFlushMeasurements = null; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; }
client.reduxMiddleware = (store) => (next) => (action) => { const {type} = action const start = performanceNow() const result = next(action) const ms = (performanceNow() - start).toFixed(0) if (!R.contains(action.type, MIDDLEWARE_ACTION_IGNORE)) { client.sendCommand('redux.action.done', {type, ms, action}) } return result }
return setTimeout(() => { var startTime = performanceNow(); cb({ didTimeout: false, timeRemaining() { return Infinity; }, }); var endTime = performanceNow(); lastRunTimeMS = (endTime - startTime) / 1000; }, delayMS);
flush() { var start = performanceNow(); var events = this._buffer.map(({evt, data}) => { var cleaned = []; var san = dehydrate(data, cleaned); if (cleaned.length) { this.setInspectable(data.id, data); } return {type: 'event', evt, data: san, cleaned}; }); this._wall.send({type: 'many-events', events}); this._buffer = []; this._waiting = null; this._lastTime = performanceNow() - start; }
scrollResponderIsAnimating: function(): boolean { const now = performanceNow(); const timeSinceLastMomentumScrollEnd = now - this.state.lastMomentumScrollEndTime; const isAnimating = timeSinceLastMomentumScrollEnd < IS_ANIMATING_TOUCH_START_THRESHOLD_MS || this.state.lastMomentumScrollEndTime < this.state.lastMomentumScrollBeginTime; return isAnimating; },
install: function({thresholdMS}: {thresholdMS: number}) { acceptableBusyTime = thresholdMS; if (installed) { return; } installed = true; lastInterval = performanceNow(); function iteration() { const now = performanceNow(); const busyTime = now - lastInterval; if (busyTime >= thresholdMS) { const stallTime = busyTime - thresholdMS; stallCount++; totalStallTime += stallTime; longestStall = Math.max(longestStall, stallTime); let msg = `JSEventLoopWatchdog: JS thread busy for ${busyTime}ms. ` + `${totalStallTime}ms in ${stallCount} stalls so far. `; handlers.forEach((handler) => { msg += handler.onStall({lastInterval, busyTime}) || ''; }); infoLog(msg); } handlers.forEach((handler) => { handler.onIterate && handler.onIterate(); }); lastInterval = now; setTimeout(iteration, thresholdMS / 5); } iteration(); },
constructor(props, context) { super(props, context); this.state = { ctorTimestamp: performanceNow(), timeToMount: 0, }; }
return function () { _this._profiles.push({ endTime: performanceNow(), name: name, startTime: startTime }); };
reset: function() { infoLog('JSEventLoopWatchdog: reset'); totalStallTime = 0; stallCount = 0; longestStall = 0; lastInterval = performanceNow(); },
callIdleCallbacks: function(frameTime: number) { if (FRAME_DURATION - (performanceNow() - frameTime) < IDLE_CALLBACK_FRAME_DEADLINE) { return; } JSTimersExecution.errors = null; if (JSTimersExecution.requestIdleCallbacks.length > 0) { const passIdleCallbacks = JSTimersExecution.requestIdleCallbacks.slice(); JSTimersExecution.requestIdleCallbacks = []; for (let i = 0; i < passIdleCallbacks.length; ++i) { JSTimersExecution.callTimer(passIdleCallbacks[i], frameTime); } } if (JSTimersExecution.requestIdleCallbacks.length === 0) { const { Timing } = require('NativeModules'); Timing.setSendIdleEvents(false); } if (JSTimersExecution.errors) { JSTimersExecution.errors.forEach((error) => require('JSTimers').setTimeout(() => { throw error; }, 0) ); } },
constructor(props: mixed, context: mixed) { super(props, context); this.start = performanceNow(); this.state = { stats: null, }; (this: any)._onDone = this._onDone.bind(this); }
function markBegin(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow(); performance.mark(markName); }
RelayMetricsRecorder.prototype.stop = function stop() { if (!this._isEnabled) { return; } this._recordingTotalTime += performanceNow() - this._recordingStartTime; this._isEnabled = false; RelayProfiler.detachAggregateHandler('*', this._measure); RelayProfiler.detachProfileHandler('*', this._instrumentProfile); };
function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } process.env.NODE_ENV !== 'production' ? warning(!currentTimerType, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; }
RelayMetricsRecorder.prototype._stopMeasurement = function _stopMeasurement(name) { var innerTime = this._profileStack.shift(); var start = this._startTimesStack.shift(); var totalTime = performanceNow() - start; this._measurements[name].aggregateTime += totalTime - innerTime; this._measurements[name].callCount++; this._profileStack[0] += totalTime; };
setTimeout(() => { const stats = { onDoneElapsed, totalWidgets, ...JSEventLoopWatchdog.getStats(), setTimeoutElapsed: performanceNow() - this.start, }; stats.avgStall = stats.totalStallTime / stats.stallCount; this.setState({stats}); console.log('onDone:', stats); }, 0);
RelayMetricsRecorder.prototype._instrumentProfile = function _instrumentProfile(name) { var _this = this; var startTime = performanceNow(); return function () { _this._profiles.push({ endTime: performanceNow(), name: name, startTime: startTime }); }; };
RelayMetricsRecorder.prototype.start = function start() { if (this._isEnabled) { return; } this._recordingStartTime = performanceNow(); this._isEnabled = true; this._profileStack = [0]; this._startTimesStack = [0]; RelayProfiler.attachAggregateHandler('*', this._measure); RelayProfiler.attachProfileHandler('*', this._instrumentProfile); };
function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(); var startTime = _lifeCycleTimerStack$.startTime; var nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime; var debugID = _lifeCycleTimerStack$.debugID; var timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; }
var queryCallback = function queryCallback(id, pendingQuery, error, results) { var time = performanceNow() - initTime; var name = pendingQuery.getDebugName(); console.timeStamp('← END: Relay query ' + id + ' ' + name); console.groupCollapsed('%cRelay query ' + id + ' ' + time / 1000 + ' ' + name, 'color:' + (error ? 'red' : 'black') + ';'); console.timeEnd(id); var query = pendingQuery.getQueryString(); console.debug('%c%s\n', 'font-size:10px; color:#333; font-family:mplus-2m-regular,menlo,' + 'monospaced;', query); error && console.error(error); results && console.log(results); console.groupEnd(); };
function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another'); lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; }
function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = null; currentTimerNestedFlushDuration = null; currentTimerDebugID = null; currentTimerType = null; }
function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } process.env.NODE_ENV !== 'production' ? warning(currentTimerType === timerType, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = null; currentTimerNestedFlushDuration = null; currentTimerDebugID = null; currentTimerType = null; }
function markEnd(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; var timeStamp = performanceNow(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); performance.clearMeasures(measurementName); }
function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another'); lifeCycleTimerHasWarned = true; } if (_isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; }
deactivateAndFlush() { if (!this._enabled) { return; } const start = this._samplesStartTime; // const for flow if (start == null) { DEBUG && console.debug('FillRateHelper: bail on deactivate with no start time'); return; } if (this._info.sample_count < _minSampleCount) { // Don't bother with under-sampled events. this._resetData(); return; } const total_time_spent = performanceNow() - start; const info: any = { ...this._info, total_time_spent, }; if (DEBUG) { const derived = { avg_blankness: this._info.pixels_blank / this._info.pixels_sampled, avg_speed: this._info.pixels_scrolled / (total_time_spent / 1000), avg_speed_when_any_blank: this._info.any_blank_speed_sum / this._info.any_blank_count, any_blank_per_min: this._info.any_blank_count / (total_time_spent / 1000 / 60), any_blank_time_frac: this._info.any_blank_ms / total_time_spent, mostly_blank_per_min: this._info.mostly_blank_count / (total_time_spent / 1000 / 60), mostly_blank_time_frac: this._info.mostly_blank_ms / total_time_spent, }; for (const key in derived) { derived[key] = Math.round(1000 * derived[key]) / 1000; } console.debug('FillRateHelper deactivateAndFlush: ', {derived, info}); } _listeners.forEach(listener => listener(info)); this._resetData(); }
return function() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var totalTime; var rv; var start; var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { ReactDefaultPerf._allMeasurements.push(entry = { exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, hierarchy: {}, totalTime: 0, created: {} }); start = performanceNow(); rv = func.apply(this, args); entry.totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations' || moduleName === 'ReactComponentBrowserEnvironment') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { ReactDefaultPerf._recordWrite('', fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { args[1].forEach(function(update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.content !== null) { writeArgs.content = update.content; } ReactDefaultPerf._recordWrite(args[0]._rootNodeID, update.type, totalTime, writeArgs); }); } else { var id = args[0]; if (moduleName === 'EventPluginHub') { id = id._rootNodeID; } else if (fnName === 'replaceNodeWithMarkup') { id = ReactDOMComponentTree.getInstanceFromNode(args[1].node)._rootNodeID; } else if (fnName === 'replaceDelimitedText') { id = getID(ReactDOMComponentTree.getInstanceFromNode(args[0])); } else if (typeof id === 'object') { id = getID(ReactDOMComponentTree.getInstanceFromNode(args[0])); } ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); } return rv; } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || fnName === '_renderValidatedComponent')) { if (this._currentElement.type === ReactMount.TopLevelWrapper) { return func.apply(this, args); } var rootNodeID = getIDOfComposite(this); var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { entry.created[rootNodeID] = true; mountStack.push(0); } ReactDefaultPerf._compositeStack.push(rootNodeID); start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; ReactDefaultPerf._compositeStack.pop(); if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else if ((moduleName === 'ReactDOMComponent' || moduleName === 'ReactDOMTextComponent') && (fnName === 'mountComponent' || fnName === 'receiveComponent')) { rv = func.apply(this, args); entry.hierarchy[getID(this)] = ReactDefaultPerf._compositeStack.slice(); return rv; } else { return func.apply(this, args); } };
return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0, created: {} }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function (update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs); }); } else { // basic format var id = args[0]; if ((typeof id === 'undefined' ? 'undefined' : _typeof(id)) === 'object') { id = ReactMount.getID(args[0]); } ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); } return rv; } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { if (this._currentElement.type === ReactMount.TopLevelWrapper) { return func.apply(this, args); } var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { entry.created[rootNodeID] = true; mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else { return func.apply(this, args); } };
var performanceNow = require('fbjs/lib/performanceNow'); type perfModule = { start: () => void, stop: () => void, } var perfModules = []; var enabled = false; var lastRenderStartTime = 0; var totalRenderDuration = 0; var RCTRenderingPerfDevtool = { onBeginLifeCycleTimer(debugID, timerType) { if (timerType === 'render') { lastRenderStartTime = performanceNow(); } }, onEndLifeCycleTimer(debugID, timerType) { if (timerType === 'render') { var lastRenderDuration = performanceNow() - lastRenderStartTime; totalRenderDuration += lastRenderDuration; } }, }; var RCTRenderingPerf = { // Once perf is enabled, it stays enabled toggle: function() { console.log('Render perfomance measurements enabled'); enabled = true;
function burnCPU(milliseconds) { const start = performanceNow(); while (performanceNow() < (start + milliseconds)) {} }