flickr.com/photos/barbourians/6662357209/                                 Timers,                                 Power Co...
New
@slicknet (Complaints:  @souders)
UI Thread             ExecuteUpdate UI            JavaScript                     flickr.com/photos/jepoirrier/954701212/
flickr.com/photos/55733754@N00/3325000738/
<button id="btn" style="font-size: 30px; padding: 0.5em    1em">Click Me</button><script>window.onload = function(){   doc...
Before ClickUI Threadtime                           UI Queue
When ClickedUI Threadtime                           UI Queue                              Update UI                       ...
When ClickedUI Thread   Update UItime                                           UI Queue               Draw down state    ...
When ClickedUI Thread   Update UI   onclicktime                                   UI Queue                                ...
When ClickedUI Thread   Update UI   onclick            Update UItime                                              UI Queue...
No UI updates while JavaScript is          executing
JavaScript May Cause UI Update<button id="btn" style="font-size: 30px; padding: 0.5em    1em">Click Me</button><script>win...
Each UI update appliesALL CHANGES since the last UI update
I gonna make      anamination!!  flickr.com/photos/oakleyoriginals/3065393607/
function naminate(element){    // start here    element.style.left = "10px";    // move to here    element.style.left = "3...
Whyyou nowork???flickr.com/photos/tudor/318123668/
function namimate(element){    // start here    element.style.left = "10px";    // move to here    element.style.left = "3...
setTimeout()
Code to                                   executevar tId = setTimeout(function(){  // do something                        ...
setTimeout()        DOES NOT SAY“Run this code after this delay”
setTimeout()             DOES SAY“Add this code to the queue after this               delay”
<button id="btn" style="font-size: 30px; padding: 0.5em    1em">Click Me</button><script>window.onload = function(){   doc...
When ClickedUI Threadtime                           UI Queue                              Update UI                       ...
When ClickedUI Thread   Update UItime                                           UI Queue               Draw down state    ...
When ClickedUI Thread   Update UI   onclicktime                                        UI Queue                           ...
When ClickedUI Thread   Update UI   onclick     Update UItime                                        UI Queue             ...
After 25msUI Thread   Update UI   onclick   Update UItime                                                 UI Queue        ...
FutureUI Thread   Update UI   onclick   Update UI   JavaScripttime                                     UI Queue
FutureUI Thread   Update UI   onclick    Update UI                    JavaScripttime                                      ...
setTimeout() sends your code into the future
setTimeout(function(){    element.style.left = "10px";}, 50);setTimeout(function(){    element.style.left = "30px";}, 100)...
Animation Loop(function(){    var delay = 100;   function moveTheThing(){       // actually move the thing       setTimeou...
(function(){    var msg = "Some reasonably long text that keeps scrolling.",        len = 25,        pos = 0,        paddi...
And More!
setTimout() all the things!!!
Problems
The default system-wide timer resolution in Windows is 15.6 ms, whichmeans that every 15.6 ms the operating system receive...
var tId = setTimeout(function(){  // do something}, 10);               What does it                 mean?
http://ejohn.org/blog/accuracy-of-javascript-time/
Animation Loop(function(){    var delay = 17;                                         Pretty   function moveTheThing(){   ...
http://ejohn.org/blog/analyzing-timer-performance/
1ms all the timers!!!
http://www.belshe.com/2010/06/04/chrome-cranking-up-the-clock/
timeBeginPeriod()
timeBeginPeriod(1)
setTimout() all the things!!!
flickr.com/photos/antonfomkin/3046849320/
Modern CPUs are narcoleptic
x86 CPU States        C0         Active        C1          Halt        C2       Stop-Clock        C3         SleepLow     ...
http://software.intel.com/en-us/articles/cpu-power-utilization-on-intel-architectures/
CPUs go to sleep when idle
The default timer resolution on Windows 7 is 15.6 milliseconds (ms).Some applications reduce this to 1 ms, which reduces t...
Web Timer Resolution TodayPlugged In     4ms    4ms     4ms    4ms           4msBattery        4ms   15.6ms   4ms   15.6ms...
Web Timer Resolution TodayBattery          4ms   10ms   10ms       10ms           4msBackground Tab    -    10ms   10ms   ...
Experiment• Hard shutdown and restart so  no other apps are running• Turn off brightness auto-adjust• Turn off screen lock...
Experiment• Test single timer at different  intervals:    • 1000ms – 10ms
Low Frequency   >= 1000msHigh Frequency < 1000ms
Time For 10% Power Use               By FrequencyMinutes   52-56     42-48          62-65
Timer frequency doesn’t matter
http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html
Experiment• Test single timer at different  intervals:    • 1000ms – 10ms• Test multiple timers at different  intervals   ...
Time For 10% Power Use                 By Count                  (same)Minutes   52-56     42-48          62-65
Number of timers doesn’t matter
Number of timers does matter        (accuracy)
http://ejohn.org/apps/timers
http://ejohn.org/apps/timers
http://ejohn.org/apps/timers
Flooding the QueueUI Threadtime                                 UI Queue                                      timer       ...
Too many timers affects rendering
Elsewhere…
http://www.w3.org/TR/css3-animations/
Optimized animations using CSS
div {    animation-name: diagonal-slide;    animation-duration: 5s;    animation-iteration-count: 10;}@keyframes diagonal-...
Hey                                     browser!                                   I want to dovar tId = setTimeout(functi...
http://www.w3.org/2010/webperf/
moz         webkithttp://www.w3.org/TR/animation-timing/
Code to                                  executevar rId = requestAnimationFrame(function(time){  // do something});// opti...
New Animation Loop(function(){   function moveTheThing(){          Hey browser!                                    I’m ani...
New Animation Loop(function(){    var element = document.getElementById("box");   function moveTheThing(){       element.s...
New Animation Loop(function(){    var element = document.getElementById("box"),        start = Date.now();   function move...
<button id="btn" style="font-size: 30px; padding: 0.5em    1em">Click Me</button><script>window.onload = function(){   doc...
When ClickedUI Threadtime                           UI Queue                              Update UI                       ...
When ClickedUI Thread   Update UItime                                           UI Queue               Draw down state    ...
When ClickedUI Thread   Update UI   onclicktime                                        UI Queue                           ...
Call to requestAnimationFrame()UI Thread   Update UI    onclicktime                                     UI Queue          ...
When ClickedUI Thread   Update UI   onclick     Update UItime                                        UI Queue             ...
Before Next FrameUI Thread   Update UI   onclick   Update UI   Changestime                                               U...
Naminate!UI Thread   Update UI   onclick   Update UI      Changes     Anim Frametime                                      ...
[requestAnimationFrame()’s framerate is] capped at 1000/(16 + N)fps, where N is the number of ms it takes your callback to...
Animate all the things!!! …with CSS and requestAnimationFrame
What about other things?
https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
Code to                            executevar iId = setImmediate(function(){  // do something                             ...
<button id="btn" style="font-size: 30px; padding: 0.5em    1em">Click Me</button><script>window.onload = function(){   doc...
When ClickedUI Threadtime                           UI Queue                              Update UI                       ...
When ClickedUI Thread   Update UItime                                           UI Queue               Draw down state    ...
When ClickedUI Thread   Update UI   onclicktime                                        UI Queue                           ...
Call to setImmediate()UI Thread   Update UI   onclicktime                                                 UI Queue        ...
When ClickedUI Thread   Update UI   onclick     Update UItime                                        UI Queue             ...
Immediately!UI Thread   Update UI   onclick    Update UI   Changestime                                                UI Q...
https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
http://www.w3.org/TR/workers/
//in pagevar worker = new Worker("process.js");worker.onmessage = function(event){     useData(event.data);};worker.postMe...
//in process.jsself.onmessage = function(event){     var items = event.data;     for (var i=0,len=items.length; i < len; i...
When ClickedUI Threadtime                           UI Queue                              Update UI                       ...
When ClickedUI Thread   Update UItime                                           UI Queue               Draw down state    ...
When ClickedUI Thread   Update UI   onclicktime                                        UI Queue                           ...
Create Web WorkerUI Thread    Update UI         onclicktime                                             UI Queue          ...
postMessage()UI Thread   Update UI   onclick       Update UItime                                         UI Queue         ...
Worker CompleteUI Thread   Update UI   onclick   Update UItime                                      UI Queue              ...
FutureUI Thread   Update UI   onclick   Update UI   onmessagetime                                     UI Queue
Recommendations
• Use as few as necessary Timers     • If multiple are necessary, use a single timer that can              accommodate all...
EtceteraMy company:     • wellfurnished.com    My blog:    • nczonline.net     Twitter    • @slicknetThese Slides:   • sli...
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
Upcoming SlideShare
Loading in...5
×

JavaScript Timers, Power Consumption, and Performance

12,934

Published on

E

Published in: Technology
2 Comments
46 Likes
Statistics
Notes
No Downloads
Views
Total Views
12,934
On Slideshare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
235
Comments
2
Likes
46
Embeds 0
No embeds

No notes for slide
  • Go to several examples
  • C0Operational state. CPU fully turned on.C1First idle state. Stops CPU main internal clocks via software. Bus interface unit and APIC are kept running at full speed.C2Stops CPU main internal clocks via hardware. State where the processor maintains all software-visible states, but may take longer to wake up through interrupts.C3Stops all CPU internal clocks. The processor does not need to keep its cache coherent, but maintains other states. Some processors have variations of the C3 state that differ in how long it takes to wake the processor through interrupts.
  • JavaScript Timers, Power Consumption, and Performance

    1. 1. flickr.com/photos/barbourians/6662357209/ Timers, Power Consumption, and PerformanceNicholas C. ZakasChief Architect, WellFurnished
    2. 2. New
    3. 3. @slicknet (Complaints: @souders)
    4. 4. UI Thread ExecuteUpdate UI JavaScript flickr.com/photos/jepoirrier/954701212/
    5. 5. flickr.com/photos/55733754@N00/3325000738/
    6. 6. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ //do something };};</script>
    7. 7. Before ClickUI Threadtime UI Queue
    8. 8. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
    9. 9. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
    10. 10. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
    11. 11. When ClickedUI Thread Update UI onclick Update UItime UI Queue Draw up state
    12. 12. No UI updates while JavaScript is executing
    13. 13. JavaScript May Cause UI Update<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ var div = document.createElement("div"); div.className = "tip"; div.innerHTML = "You clicked me!"; document.body.appendChild(div); };};</script>
    14. 14. Each UI update appliesALL CHANGES since the last UI update
    15. 15. I gonna make anamination!! flickr.com/photos/oakleyoriginals/3065393607/
    16. 16. function naminate(element){ // start here element.style.left = "10px"; // move to here element.style.left = "30px"; // then to here element.style.left = "50px"; // finally to here element.style.left = "70px";}
    17. 17. Whyyou nowork???flickr.com/photos/tudor/318123668/
    18. 18. function namimate(element){ // start here element.style.left = "10px"; // move to here element.style.left = "30px"; // then to here element.style.left = "50px"; Last state // finally to here wins element.style.left = "70px";}
    19. 19. setTimeout()
    20. 20. Code to executevar tId = setTimeout(function(){ // do something Delay in}, 1500); milliseconds// optionalclearTimeout(tId)
    21. 21. setTimeout() DOES NOT SAY“Run this code after this delay”
    22. 22. setTimeout() DOES SAY“Add this code to the queue after this delay”
    23. 23. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ setTimeout(function() { //do something }, 25); };};</script>
    24. 24. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
    25. 25. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
    26. 26. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
    27. 27. When ClickedUI Thread Update UI onclick Update UItime UI Queue Draw up state
    28. 28. After 25msUI Thread Update UI onclick Update UItime UI Queue JavaScript Added to back of queue
    29. 29. FutureUI Thread Update UI onclick Update UI JavaScripttime UI Queue
    30. 30. FutureUI Thread Update UI onclick Update UI JavaScripttime UI Queue Update UI If the JavaScript changes the UI, it triggers another update
    31. 31. setTimeout() sends your code into the future
    32. 32. setTimeout(function(){ element.style.left = "10px";}, 50);setTimeout(function(){ element.style.left = "30px";}, 100);setTimeout(function(){ element.style.left = "50px";}, 150);setTimeout(function(){ element.style.left = "70px";}, 200);
    33. 33. Animation Loop(function(){ var delay = 100; function moveTheThing(){ // actually move the thing setTimeout(moveTheThing, delay); } setTimeout(moveTheThing, delay);}());
    34. 34. (function(){ var msg = "Some reasonably long text that keeps scrolling.", len = 25, pos = 0, padding = msg.replace(/./g, " ").substr(0,len) finalMsg = padding + msg, delay = 100; function updateText(){ var curMsg = finalMsg.substr(pos++, len); window.status = curMsg; if (pos == finalMsg.length){ pos = 0; } setTimeout(updateText, delay); } setTimeout(updateText, delay);}());
    35. 35. And More!
    36. 36. setTimout() all the things!!!
    37. 37. Problems
    38. 38. The default system-wide timer resolution in Windows is 15.6 ms, whichmeans that every 15.6 ms the operating system receives a clock interruptfrom the system timer hardware.-Timers, Timer Resolution, and Development of Efficient Code (Microsoft)
    39. 39. var tId = setTimeout(function(){ // do something}, 10); What does it mean?
    40. 40. http://ejohn.org/blog/accuracy-of-javascript-time/
    41. 41. Animation Loop(function(){ var delay = 17; Pretty function moveTheThing(){ please?!?! // actually move the thing setTimeout(moveTheThing, delay); } setTimeout(moveTheThing, delay);}());
    42. 42. http://ejohn.org/blog/analyzing-timer-performance/
    43. 43. 1ms all the timers!!!
    44. 44. http://www.belshe.com/2010/06/04/chrome-cranking-up-the-clock/
    45. 45. timeBeginPeriod()
    46. 46. timeBeginPeriod(1)
    47. 47. setTimout() all the things!!!
    48. 48. flickr.com/photos/antonfomkin/3046849320/
    49. 49. Modern CPUs are narcoleptic
    50. 50. x86 CPU States C0 Active C1 Halt C2 Stop-Clock C3 SleepLow C4 Deep SleepPower C5 Enhanced Deep Sleep C6 Deep Power Down
    51. 51. http://software.intel.com/en-us/articles/cpu-power-utilization-on-intel-architectures/
    52. 52. CPUs go to sleep when idle
    53. 53. The default timer resolution on Windows 7 is 15.6 milliseconds (ms).Some applications reduce this to 1 ms, which reduces the battery runtime on mobile systems by as much as 25 percent.-Timers, Timer Resolution, and Development of Efficient Code (Microsoft) Laptops!
    54. 54. Web Timer Resolution TodayPlugged In 4ms 4ms 4ms 4ms 4msBattery 4ms 15.6ms 4ms 15.6ms 4msBackground 1s 1s 4ms 1s* 4ms * Internet Explorer 10
    55. 55. Web Timer Resolution TodayBattery 4ms 10ms 10ms 10ms 4msBackground Tab - 10ms 10ms 10ms 1sBackground App - * * * 1s * “Catches up” when switched back
    56. 56. Experiment• Hard shutdown and restart so no other apps are running• Turn off brightness auto-adjust• Turn off screen locking• Leave WiFi/Mobile on• Load test page in browser• Profit!
    57. 57. Experiment• Test single timer at different intervals: • 1000ms – 10ms
    58. 58. Low Frequency >= 1000msHigh Frequency < 1000ms
    59. 59. Time For 10% Power Use By FrequencyMinutes 52-56 42-48 62-65
    60. 60. Timer frequency doesn’t matter
    61. 61. http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html
    62. 62. Experiment• Test single timer at different intervals: • 1000ms – 10ms• Test multiple timers at different intervals • 1000ms – 10ms x 10
    63. 63. Time For 10% Power Use By Count (same)Minutes 52-56 42-48 62-65
    64. 64. Number of timers doesn’t matter
    65. 65. Number of timers does matter (accuracy)
    66. 66. http://ejohn.org/apps/timers
    67. 67. http://ejohn.org/apps/timers
    68. 68. http://ejohn.org/apps/timers
    69. 69. Flooding the QueueUI Threadtime UI Queue timer timer timer
    70. 70. Too many timers affects rendering
    71. 71. Elsewhere…
    72. 72. http://www.w3.org/TR/css3-animations/
    73. 73. Optimized animations using CSS
    74. 74. div { animation-name: diagonal-slide; animation-duration: 5s; animation-iteration-count: 10;}@keyframes diagonal-slide { Hey browser! from { I’m animating! left: 0; top: 0; } to { left: 100px; top: 100px; } }
    75. 75. Hey browser! I want to dovar tId = setTimeout(function(){ something // do something later}, 1500); Could be animation. Could be polling. Don’t sweat it.
    76. 76. http://www.w3.org/2010/webperf/
    77. 77. moz webkithttp://www.w3.org/TR/animation-timing/
    78. 78. Code to executevar rId = requestAnimationFrame(function(time){ // do something});// optional Time whenclearAnimationFrame(rId) the paint will happen
    79. 79. New Animation Loop(function(){ function moveTheThing(){ Hey browser! I’m animating! // actually move the thing requestAnimationFrame(moveTheThing); } requestAnimationFrame(moveTheThing);}());
    80. 80. New Animation Loop(function(){ var element = document.getElementById("box"); function moveTheThing(){ element.style.left = (element.offsetLeft + 5) + "px"; requestAnimationFrame(moveTheThing); } requestAnimationFrame(moveTheThing);}());
    81. 81. New Animation Loop(function(){ var element = document.getElementById("box"), start = Date.now(); function moveTheThing(time){ var since = (time || Date.now()) – start; element.style.left = (element.offsetLeft + since)+ "px"; requestAnimationFrame(moveTheThing); } requestAnimationFrame(moveTheThing);}());
    82. 82. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ requestAnimationFrame(function() { //do something }); };};</script>
    83. 83. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
    84. 84. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
    85. 85. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
    86. 86. Call to requestAnimationFrame()UI Thread Update UI onclicktime UI Queue Update UI Changes Anim Frame
    87. 87. When ClickedUI Thread Update UI onclick Update UItime UI Queue Changes Draw up state Anim Frame
    88. 88. Before Next FrameUI Thread Update UI onclick Update UI Changestime UI Queue Anim Frame
    89. 89. Naminate!UI Thread Update UI onclick Update UI Changes Anim Frametime UI Queue Draw whatever changes are necessary
    90. 90. [requestAnimationFrame()’s framerate is] capped at 1000/(16 + N)fps, where N is the number of ms it takes your callback to execute.If your callback takes 1000ms to execute, then its capped at under1fps. If your callback takes 1ms to execute, you get about 60fps.-Boris Zbarsky (Mozilla) via Paul Irish (Google)
    91. 91. Animate all the things!!! …with CSS and requestAnimationFrame
    92. 92. What about other things?
    93. 93. https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
    94. 94. Code to executevar iId = setImmediate(function(){ // do something msSetImmediate()}); msClearImmediate()// optionalclearImmediate(iId)
    95. 95. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><script>window.onload = function(){ document.getElementById("btn").onclick = function(){ setImmediate(function() { //do something }); };};</script>
    96. 96. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
    97. 97. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
    98. 98. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
    99. 99. Call to setImmediate()UI Thread Update UI onclicktime UI Queue Update UI Changes Always added after the last UI update in the queue
    100. 100. When ClickedUI Thread Update UI onclick Update UItime UI Queue Changes Draw up state
    101. 101. Immediately!UI Thread Update UI onclick Update UI Changestime UI Queue
    102. 102. https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html
    103. 103. http://www.w3.org/TR/workers/
    104. 104. //in pagevar worker = new Worker("process.js");worker.onmessage = function(event){ useData(event.data);};worker.postMessage(values);
    105. 105. //in process.jsself.onmessage = function(event){ var items = event.data; for (var i=0,len=items.length; i < len; i++){ process(items[i]); } self.postMessage(items);};
    106. 106. When ClickedUI Threadtime UI Queue Update UI onclick Update UI
    107. 107. When ClickedUI Thread Update UItime UI Queue Draw down state onclick Update UI
    108. 108. When ClickedUI Thread Update UI onclicktime UI Queue Update UI
    109. 109. Create Web WorkerUI Thread Update UI onclicktime UI Queue Update UI Creates a backgroundthread/process/etc.
    110. 110. postMessage()UI Thread Update UI onclick Update UItime UI Queue process
    111. 111. Worker CompleteUI Thread Update UI onclick Update UItime UI Queue onmessage
    112. 112. FutureUI Thread Update UI onclick Update UI onmessagetime UI Queue
    113. 113. Recommendations
    114. 114. • Use as few as necessary Timers • If multiple are necessary, use a single timer that can accommodate allAnimation • Use CSS transitions and animations first • If not possible, use requestAnimationFrame() Other • Use web workers for efficient data processing • If no other options, use timers (see first point)
    115. 115. EtceteraMy company: • wellfurnished.com My blog: • nczonline.net Twitter • @slicknetThese Slides: • slideshare.net/nzakas
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×