500 likes | 754 Views
Windows Vista: Developing Power-Aware Applications. Geralyn Miller Program Manager Windows Laptop PC Microsoft Corporation gemiller@microsoft.com. Pat Stemen FUN319 Program Manager Core Platform Architecture Microsoft Corporation patste@microsoft.com. Agenda.
E N D
Windows Vista: Developing Power-Aware Applications Geralyn Miller Program Manager Windows Laptop PC Microsoft Corporation gemiller@microsoft.com Pat Stemen FUN319 Program Manager Core Platform Architecture Microsoft Corporation patste@microsoft.com
Agenda • Windows Vista Power Management Goals • Power-Aware Applications • Handling Sleep Transitions • Power versus Performance • Integrating with Windows Power Policy • Testing for Power Management
Windows Vista Power Management Goals • Simplify the user experience • Enhance and extend power management usage models • Improve the reliability of sleep transitions • Predictable behavior • Visibility into power management actions • Extensive diagnostic tracing • Enable maximum energy savings • Mobile PC battery life • Desktop power consumption
Windows VistaMobile PC Pillars More Places More Scenarios Smooth Transitions More time on Windows each day New mobile experiences, new value Eliminate existing pain points Fast Startup Power Management Connectivity Synchronization Displays Natural Input/Output Context Awareness Auxiliary Displays Security Backup & Recovery Collaboration Digital Ink Mobile Media
Power-Aware Applications • To achieve power management goals, applications must be power-aware • Designed and tested for power management • Applications must handle sleep transitions seamlessly • You can differentiate your application with power management features • Handle power management events • Scale behavior based on user’s power preference and state of the machine • Integrate with Windows power policy
Enabling Maximum PC Energy Savings • Windows Vista will, by default, enable energy-saving features on all PCs • Sleep is the default “off” behavior on both desktops and mobiles • Desktop systems will have monitor blanking and sleep idle timeouts • Aggressive power policy defaults for mobile PCs • Windows Vista addresses the principle power management adoption blockers • Removes need to be Administrator to change policy settings • Supports Group Policy control of power settings • Provides a rich power policy command-line tool • Features reliable and deterministic sleep transitions
Handling Sleep TransitionsOverview • Maximizing PC energy savings requires reliable sleep transitions • But, failed transitions are the primary sleep adoption blocker • Component vetoes are the primary cause • Roughly 1/3 of all sleep failures • Drivers may veto sleep requests • Services may silently fail sleep • Some applications display warnings, some do not • Some may display warnings – with the laptop lid closed!
Handling Sleep TransitionsOverview • Component vetoes lead to great user frustration and distrust of power management • System did not do what the user asked • Worst case scenario • Laptop in a bag fails to sleep, or wakes and fails to return to sleep • Battery drains, system overheats, laptop is unusable when needed, possible data loss • Users turn off sleep and use shutdown
Handling Sleep TransitionsOverview • Investigations show that applications and services abuse the ability to veto • Veto instead of develop and test for power management • Veto to prevent potential network connectivity loss • Same component may handle network connectivity well outside of sleep / resume
Handling Sleep TransitionsWindows Vista changes • Windows Vista will not query user mode components when entering sleep • PBT_APMQUERYSUSPEND event will not be sent • Windows Vista will continue to notify user mode components when entering sleep • PBT_APMSUSPEND event is sent • Timeout has been reduced from 20s to 2s • Use this event to do limited cleanup before the suspend transition
Handling Sleep TransitionsApplications • Do not depend on blocking a sleep state transition • An event will always be sent when the system resumes from sleep • PBT_APMRESUME, PBT_APMRESUMECRITICAL, PBT_APMRESUMEAUTOMATIC • Use this event to automatically restart a task that did not complete because of a sleep state transition • PBT_APMxxx events are delivered with the WM_POWERBROADCAST message • More information available in the Platform SDK
Handling Sleep TransitionsIdle to Sleep • Sleep idle timeout • Transitions the system to sleep after period of inactivity • Reduces power consumption when the PC is not in use • User-configurable, but enabled by default in Windows Vista on both mobiles and desktops • Applications may temporarily disable sleep idle timer to ensure system availability • e.g., burning a CD, recording a TV show • Only disable the timer if absolutely necessary, users expect the system to idle to sleep
Handling Sleep TransitionsIdle to Sleep • SetThreadExecutionState API • Temporarily disables the sleep idle timer • Does not prevent user-initiated sleep transitions • Button press, lid switch, Start -> Sleep, etc. • Usage of SetThreadExecutionState • Disable the sleep idle timer SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS); • Process Task • When complete, re-enable the sleep idle timer SetThreadExecutionState(ES_CONTINUOUS); • If your process is unexpectedly terminated, the power manager will automatically clear the ES_SYSTEM_REQUIRED reference
Optimizing For Low Power Processor • Processor power management is a primary method for the platform to reduce power consumption • However, applications can easily prevent processor power management effectiveness • When idle, OS directs CPU to a low power sleep state • ACPI C-states (C1-C4) • Processor is halted and not executing instructions • Processor performance states • Dynamic voltage and frequency scaling technologies
Optimizing For Low Power Best Practice: Processor • To ensure processor power management effectiveness, applications should avoid • Increasing the timer tick frequency • If you must increase the timer interval, restore it when work requiring the increase is complete • Spinning in tight code loops • Use registration / notification APIs, events instead of polling • Scheduling frequent periodic timers to poll for work or hardware
Optimizing For Low Power Best Practice: Processor • Applications should • Eliminate or reduce polling intervals while on battery power • Use Windows Vista asynchronous notifications for power management events instead of polling • Use PeekMessage loop for as little time as possible • PeekMessage prevents processor idle states • Use WaitMessage when not background processing • Treat power consumption as a performance metric • In general, performance optimizations will often yield CPU power savings
Optimizing For Low Power Best Practice: Processor • Be aware of your app’s CPU utilization on both AC and DC power • Profile your application’s effect on C-state, P-state utilization on laptops running on DC • Use Windows Performance Monitor (perfmon.msc)
Power Versus PerformanceDisplay • The display backlight represents ≈ 33% of a laptop’s power budget when idle • A short display blanking timeout is required to conserve laptop battery power • Windows Vista default power plans have short display blanking timeouts • Timeout is longer on AC than on DC power
Power Versus PerformanceBest Practice: Display • Be conscious of your app’s use of the display • Don’t prevent screen blanking when not actively displaying to the user • For example (this is incorrect) • Application is minimized and has called • SetThreadExecutionState(ES_DISPLAY_REQUIRED) • Don’t render graphics when display is off • 3D graphics and moving visuals use large amounts of CPU/GPU and increase system power consumption • Utilize the monitor on/off notification GUID in Windows Vista
Optimizing For Low Power Hard Disk Drive (HDD) • HDD power consumption is ≈ 8% of a laptop’s total power budget • Windows power policy will attempt to spin down the HDD when the disk idle timer expires • Significant power is consumed by the energy required to spin up the HDD
Optimizing For Low Power Best Practice: Hard Disk Drive (HDD) • Analyze your application’s use of the HDD • Cache, pre-fetch data where possible • Avoid regular, periodic flushes to disk • Flushing registry keys • E.g. Auto-save less frequently when the system is on battery power • Leverage Windows Vista power event notifications to schedule background work • Register with GUID_BACKGROUND_TASK_NOTIFICATION • Notification indicates that the system is not idle • Now is an appropriate time for background work • Disk is already spinning
Windows Power Policy • All power plans in Windows Vista have a personality • Power Saver • Automatic • High Performance • Windows Vista provides default power plans (instances) of each personality type • The identification GUID of the default power plans indicates the personality of all other power plans • Power plans may be easily discovered and changed by users • Active power scheme personality can be broadcast to interested components • Allows applications and devices to understand and respond to user’s power intent
Handling Common Power Events • Applications may wish to handle common power management events • AC / DC power state change • Power scheme personality change • Monitor on / off • Battery capacity remaining • Historically, applications need to poll for status change • Eg, GetSystemPowerStatus API for battery capacity, AC line status
Use Windows Vista asynchronous notifications for common power events Eliminates need to poll Register with RegisterPowerSettingNotification API Power event notifications (PBT_POWERSETTINGCHANGE) are delivered with the WM_POWERBROADCAST message lParam is a pointer to POWERBROADCAST_SETTING Includes GUID of power setting which changed New value of the power setting Initial notification delivered shortly after registration Handling Common Power Events
Using Windows Vista Power APIs In a Windows Forms Application Geralyn Miller Program Manager Windows Laptop PC
Handling Common Power Events • AC / DC power state change • Register with GUID_ACDC_POWER_SOURCE • Callback value is • AC (utility power) • DC (battery power) • Short-term DC (UPS device) • Useful for knowing when the system transitions to UPS power
Handling Common Power Events • Power plan personality change • Register with GUID_POWER_SCHEME_PERSONALITY • Callback value is GUID indicating scheme personality • Power Saver • Automatic • High Performance • Can be used to implement simple power saving behavior
Handling Common Power Events • Monitor on / off • Register with GUID_MONITOR_POWER_ON • Notification value indicates if the primary video device is on or off • Useful for media applications • Applications may stop rendering video or other content when the display is off to save power
Integrating With Windows Power PolicyOverview • Applications have several options for reducing performance to conserve power • Scale back the user experience • Graphics richness • Reduce the frequency of data updates • Reduce CPU work loads • Number of threads, thread priorities • Use hardware (not software) rendering for graphics • Turn off or constrain background processing • Defer unnecessary tasks
Scaling An Avalon Application According To Power Policy Geralyn Miller Program Manager Windows Laptop PC
Integrating With Windows Power Policy • To integrate any component with Windows power policy • Define a new power setting • Install the new power setting • Register for change notification on the new power setting • Respond to change notifications
Scaling BehaviorDefining custom power settings • Power setting attributes • Identification GUID • Textual name, description • Setting values for AC, DC • Range of values • List of discrete values • Specify default values for each default power plan • Correct defaults are critical • Assume users will not go to the Power Control Panel to configure the new setting
Integrating With Windows Power PolicyInstalling custom power settings • INF or API-based installation • INF method is the preferred (and easiest) method • New INF directives to support power setting installation • Use in device installation INF or separate INF executed during application installation • Execute separate INF during application installation using InstallHinfSection API rundll32.exe setupapi.dll,InstallHinfSection mySection 128 PathToMyInf.inf Power setting installation requires administrative privileges
; Indicate one or more sections for ; new power settings AddPowerPolicy=MyAppPowerSetting ; Section to add the setting [MyAppPowerSetting] Policy = <Power Setting GUID>, “Friendly Name”, “Description”, <reference to icon> SettingRange = 0, 100, “%” ; Specify default values Default = %MAX_POWERSAVINGS_GUID%, %AC%, 50 Default = %MAX_POWERSAVINGS_GUID%, %DC%, 50 Default = %AUTOMATIC_POWERSAVINGS_GUID%, %AC%, 95 Default = %AUTOMATIC_POWERSAVINGS_GUID%, %DC%, 50 Default = %MAX_PERFORMANCE_GUID%, %AC%, 100 Default = %MAX_PERFORMANCE_GUID%, %DC%, 100 Integrating With Windows Power PolicyInstalling custom power settings
Integrating With Windows Power PolicyRegistering for setting notifications • Register for change notifications on the new power setting • Use the power event/setting notification API: RegisterPowerSettingNotification • Register within application initialization code • Register for notification with unique GUID • Deregister when your application is closed
Integrating With Windows Power PolicyRespond to setting notification • Respond to the power setting change notification • Change notification will occur when the power setting value changes • Active power scheme change • AC / DC transition • User changes setting value • Change notification occurs shortly after registration
Testing For Power Management • Power-aware applications are tested for power management • Test your application’s behavior for all power management scenarios • Sleep / resume • Idle to sleep • Mobile PC / lid closure • AC, DC • Use tools available in the WDK to automate sleep transition testing • Custom tests can be built using the SetSystemPowerState and SetWaitableTimer APIs
Summary • Windows Vista enables power saving settings (and use of sleep / resume) by default on all PCs • Applications must seamlessly handle sleep transitions • Applications can use power management best practices to optimize for low power consumption and help extend battery life • Windows Vista enables applications to easily integrate with system power policy • Applications can scale behavior according topower preference
Call To Action • Design and Test your application for power management! • Register for Windows Vista beta program, provide feedback • Take advantage of power saving features and opportunities to differentiate your products • Use power management best practices when developing your application • Integrate your application with system power policy
Community Resources • At PDC • Labs: “Mobile PC: Building Energy Smart Windows Vista Applications (C#)” • Lab is on the Tablet PCs in the Presentation Track Area • Fundamentals Track Lounge: Friday, 8:30-11:30 AM • Get spotted with this button for a chance to win a Tablet PC! • After PDC • If you missed this related session, watch it on the DVD • FUN319: “Developing Power-Aware Applications for Windows Vista” • MSDN Dev Center: http://msdn.microsoft.com/windowsvista • MSDN Forums: http://forums.microsoft.com/msdn • “Mobile PC and Tablet PC” category
Additional Resources • White paper detailing Power Policy APIs and power setting installation • http://go.microsoft.com/fwlink/?LinkId=51286 • How to setup a new developer environment on Windows Vista in order to take advantage of the Mobile PC and Tablet PC SDK features, along with Windows Presentation Foundation at msdn.microsoft.com/mobilepc/pdc05 • Mobile PC and Tablet PC Developer Center: msdn.microsoft.com/MobilePC • Download SDKs, code samples, articles • Fabrikam Fine Furniture Reference Application: End-to-end reference application demonstrating Mobile PC and Tablet PC best practices for business applications. • Arcs of Fire: Classic artillery duel game demonstrating how to use gestures, use pressure sensitivity, draw landscapes, and more. This uses the new Tablet PC Game SDK. • Tablet PC ISV Partner Program: TabletPCPartners.com
© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
Appendix: Windows Power Management Definitions • Suspend to RAM (ACPI S3 state) • “Standby” • Very fast startup • State preserved in RAM (volatile) • Suspend to HDD (ACPI S4 state) • “Hibernate” • Start up time < boot time • State preserved in non-volatile storage • Hybrid Sleep • Combines Standby and Hibernate • Suspend to RAM and HDD at the same time • System can wake on: • User-initiated action (button press, lid) • Wake-capable device • Real Time Clock (RTC) - scheduled task
Appendix: Windows Power Management Definitions • System power source • AC (utility power) • DC (battery power) • Long term battery (laptop computer) • Short term battery (UPS) • Device power states • Low power idle or sleep states
Appendix: Handling Sleep Transitions EXECUTION_STATESetThreadExecutionState( EXECUTION_STATEesFlags ); esFlags values
Appendix: Registering for Windows Power Policy Notifications • RegisterPowerSettingNotification • USER mode, requires message handler HPOWERNOTIFY RegisterPowerSettingNotification( IN HANDLE hRecipient, IN LPCGUID PowerSettingGuid, IN DWORD Flags );
Appendix: Responding to Windows Power Policy Notifications • POWERBROADCAST_SETTING • lParam of PBT_POWERSETTINGCHANGE event typedef struct { GUID PowerSetting; DWORD DataLength; UCHAR Data[1]; } POWERBROADCAST_SETTING, *PPOWERBROADCAST_SETTING;
Appendix: Unregistering for Windows Power Policy Notifications • UnRegisterPowerSettingNotification • USER mode, requires message handler HPOWERNOTIFY UnRegisterPowerSettingNotification( IN HANDLE hRecipient );
Appendix: Mobile PC Pillar Definitions More Places MoreAvailable More Scenarios Fast Startup • 2-3 second resume from ‘sleep’ • 10-15 second boot/ disk resume • Simplified UX • Fast off Power Mgmt • Reliable power state transitions • Simplified UX • New permissions; Group Policy • Device power management • Hybrid hard drives Connectivity • Wireless performance • Wireless security & extensibility • Group policy support • Network diagnostics • Easy network setup, join and resource discovery • VPN-less remote access Synchronization • PC/PC & PC/server synch • Integrated device synch • Performance improvements • Sync Center: Consolidated UX Displays • External display and projector transitions • Auto-configuration & restore Natural Input/Output • ‘Flicks’ input gestures • Pen / shell integration • TIP auto-complete • Handwriting personalization • Ink Watson • Touch screen support • High DPI support & font scaling Context Awareness • Windows Mobility Center • Presentation settings • Smart default printer switching Auxiliary Displays • Quick access to PIM data, system status • Audio playback Security • HW-enabled file & system protection Backup & Recovery • Easy data backup & restore Collaboration • Windows Meeting Space: PC to PC broadcast & file sharing within groups • Discovery of nearby people • Ad hoc wireless networking • Networked projection Digital Ink • Note taking & drawing • Search ink notes • Sticky notes • Annotating documents Mobile Media • Instant media playback