/*
* Let's say we want to know the CPU cost from some action
* that includes async tasks. We can do this with zones!
*/
/*
* For this demo, we're going to sort an array using an async
* algorithm when a button is pressed.
*/
function sortAndPrintArray (unsortedArray) {
profilingZoneSpec.reset();
asyncBogosort(unsortedArray, function (sortedArray) {
console.log(sortedArray);
console.log('sorting took ' + profilingZoneSpec.time() + ' of CPU time');
});
}
/*
* This is a really efficient algorithm.
*
* First, check if the array is sorted.
* - If it is, call the wrapCallback
* - If it isn't, randomize the array and recur
*
* This implementation is async because JavaScript
*/
function asyncBogosort (arr, cb) {
setTimeout(function () {
if (isSorted(arr)) {
cb(arr);
} else {
var newArr = arr.slice(0);
newArr.sort(function () {
return Math.random() - 0.5;
});
asyncBogosort(newArr, cb);
}
}, 0);
}
function isSorted (things) {
for (var i = 1; i < things.length; i += 1) {
if (things[i] < things[i - 1]) {
return false;
}
}
return true;
}
/*
* Bind button
*/
function main () {
var unsortedArray = [3,4,1,2,7];
setTimeout( function () {
sortAndPrintArray(unsortedArray);
},1000);
}
/*
* This zone starts a timer at the start of each taskEnv,
* and stops it at the end. It accumulates the total run
* time internally, exposing it via `zone.time()`
*
* Note that this is the time the CPU is spending doing
* bogosort, as opposed to the time from the start
* of the algorithm until it's completion.
*/
var profilingZoneSpec = (function () {
var time = 0,
// use the high-res timer if available
timer = performance ?
performance.now.bind(performance) :
Date.now.bind(Date);
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.