performance less responsive to the user consumes resources from foreground applications impacts...
TRANSCRIPT
Improving System Performance by Creating Efficient Background Activities
Vikram SinghProgram Manager IIMicrosoft Corporation
Objectives
Help developers understand the importance of designing efficient background activity Provide developers with information and tools on efficient background activity designs
Agenda
IntroductionBackground activity impactChoosing the right modelWindows® 7 trigger-start servicesTask scheduler conditions and triggersSecurity and performance recommendationsCall to actionResources
Background Activity Primer
System activities that are not directly initiated by the user
Service, scheduled task, some COM processes (such as a COM service), WMI provider, and so on
Part of nearly every usage scenarioSearch indexingSystem security and maintenanceNetwork managementDevice managementSystem configuration
Performance• Less responsive to the user• Consumes resources from
foreground applications• Impacts boot, shutdown,
and logoff
Reliability• Memory leaks• System crashes, hangs• Dependent application
crashes
Security• An activity can require
system privileges • A successful attack can
compromise the entire system
Power Consumption
• Extra disk, CPU utilization• Decrease in battery life• Prevents idle efficiencies
Impact of Background Activity
Resource QuantityFile I/O 47,286
Copy-on-write (COW) pages 4,656 (~18MB)
Memory pages (Total) 15,967 (~60MB)
Registry operations 38,508
Threads 367
Case Study on Impact of Background Activity
Reviewed 49 Windows servicesThese services are not critical for boot and logonThey are critical and required for their individual features
Clean IT0
20
40
24.746.1
Boot Timeseconds
Clean IT0
153045
25.6 30
Shutdown Timeseconds
Clean IT0%
4%
8%
1.01%6.04%
Idle CPU Utilization15-second trace
Clean IT0
20,000
40,000
10,192 31,401
Disk Read Count15-second trace
Impact on Performance
Comparison of a clean Windows Vista® installation to an IT image that included 10 third-party services
Designing for Efficiency
Choose the right modelWindows service or scheduled task?
Leverage the latest Windows infrastructureTrigger-start services in Windows 7
Optimize performanceEliminate unnecessary privilegesEvaluate and measureIterate on optimizations
Win
dow
s S
ervi
ce • Continuous activity from boot to shutdown
• SCM (Service Control Manager) programming model
• Can specify dependency
Sch
edul
ed T
ask
• Short duration action
• Idle activity• Take action
on user logon• Standalone
executable or out-of-process COM server
• Generally execute
during a user session
Choosing the Right Model
Windows Services: Auto_Start
Auto_Start start type enables the service to launch at bootThis is the most commonly used service start type
Easy for developers because service is always running
ProblemsStartup time adds to boot timeAdds to system base footprintMany Auto_Start services wait for rare events
Windows Services: Trigger-Start
Windows 7 trigger-start services centralize environmental detection logic
SCM registers for interesting system eventsDevice arrivalIP address availabilityJoin or leave domainGroup policy updateFirewall port open or closeCustom Event Tracing for Windows (ETW) events
SCM starts or stops registered services based on events
Converting a Service to Trigger-Start
demo
Service Name Service Purpose Trigger Type
AELookupSvcProcesses application compatibility cache requests for applications as they are launched
Custom ETW
BDESVC Provides BitLocker client services for user interface and auto-unlocking of data volumes Custom ETW
BTHSERV Supports discovery and association of remote Bluetooth devices Device
SensorsMTPMonitorMonitors MTP (Media Transfer Protocol) sensors, such as a cell phone with a GPS receiver, to communicate sensor data to programs
Device
TabletInputService Enables pen and ink functionality Device
WinDefend Protects against spyware and potentially unwanted software Group Policy
Example of Trigger-Start Services
Service Shutdown – Best Practices
Service should self-stop immediately or after pre-determined idle time when task is completedOn system shutdown
Do not set SERVICE_ACCEPT_SHUTDOWN unless requiredNo need to free memory if the service is in a standalone processTarget less than 200ms for completing shutdown notification
Service Control Handler – Best Practices
Do not block callsWaitForSingleObject, CreateFile, RPCs, and othersStrive for lock-free code
Execute work items in a thread poolFollow the MSDN guidelines for specific return codesUse SERVICE_CONTROL_STOP
Call SetServiceStatus(SERVICE_STOP_PENDING)Post stop work to a thread poolCall SetServiceStatus(SERVICE_STOPPED)
SERVICE_REQUIRED_PRIVILEGES_INFO srpInfo;
WCHAR mszPrivilegeBuffer[25] = {0};
hSCManager=OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
hFooService=OpenService(hSCManager, wszSERVICENAME, SERVICE_CHANGE_CONFIG);
( VOID ) StringCbCopy ( mszPrivilegeBuffer, sizeof(mszPrivilegeBuffer), L”SeChangeNotifyPrivilege”);
srpInfo.pmszRequiredPrivileges = mszPrivilegeBuffer;
ChangeServiceConfig2 ( *phService, SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO,
&srpInfo) )
Service Security – Best Practices
Run with the lowest privilege level needed to perform task
Use LocalService/ NetworkServiceAvoid using LocalSystem
Express required privilegesSCM automatically removes all others
Remove unneeded privileges, such as SeImpersonatePrivilege
Task Scheduler(schedule)
Power Efficiency Diagnostics
(powercfg.exe)
Kernel
Detects Idle Condition
Launches Task
Scheduled Task Example
Power Efficiency DiagnosticsPower problem analysisExecutes every 2 weeks when the system is idleRequires SYSTEM privilege to access NT Kernel Logger Saves report data for the userUploads CEIP (Customer Experience Improvement Program) data to Microsoft
Task Triggers
CalendarBootLogonIdleEvent log itemWorkstation lockWorkstation unlock
Task Conditions
Idle conditionStop when not idleAC power onlyStop on batteryWake computer from sleepSpecific or any network connection
Task Recommendations
Use the idle condition to prevent background activity from interrupting the userEnable the power condition – do not run when the system is on batteryEnable the network condition if the task requires network connectivity, such as downloading a software update
Performance and Power
Background activity can degrade PC performanceAdds to the base footprint of the systemInterferes with foreground user activityResource utilization is directly tied to power consumption
Targets when system is idleLess than 2% CPU activityNo disk activity
Evaluate and measure performanceUse XPerfXPerf is part of the Windows Performance Tools Kit
Call to Action
Understand that background activity has tangible impact on system qualitySelect the right model: service or taskUse Windows 7 trigger-start instead of Auto_StartConfigure your service or task to use the most restrictive set of security privilegesLeverage scheduled task idle, power, and network conditionsMeasure using Windows Performance Tools Kit (XPerf)Fill out the evaluation form for this presentation
Resources
Paper - Developing Efficient Background Processes for Windowshttp://go.microsoft.com/fwlink/?LinkId=128622
Paper - Services in Windows Vistahttp://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/Vista_Services.doc
MSDN - Service Control Managerhttp://msdn.microsoft.com/en-us/library/ms685150(VS.85).aspx
MSDN - Task Schedulerhttp://msdn.microsoft.com/en-us/library/aa383614.aspx
Windows Performance Tools Kithttp://www.microsoft.com/whdc/system/sysperf/perftools.mspx
Windows Summit Session - Building High-Performing Windows Applications by Using the Windows Performance Toolkit (SOW-111)
© 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation.MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.