Windows 性能
本文档提供了一些性能优化建议,您可以将其应用于 Windows 主机,以加快它们的速度,特别是在使用 Ansible 的情况下,以及通常情况下。
优化 PowerShell 性能以减少 Ansible 任务开销
为了将 PowerShell 的启动速度提高约 10 倍,请在管理员会话中运行以下 PowerShell 代码片段。预计需要几十秒钟。
注意
如果本地映像已由 ngen 任务或服务创建,您将不会观察到性能差异(但此时此代码片段的执行速度会比其他情况下快)。
function Optimize-Assemblies {
param (
[string]$assemblyFilter = "Microsoft.PowerShell.",
[string]$activity = "Native Image Installation"
)
try {
# Get the path to the ngen executable dynamically
$ngenPath = [System.IO.Path]::Combine([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory(), "ngen.exe")
# Check if ngen.exe exists
if (-Not (Test-Path $ngenPath)) {
Write-Host "Ngen.exe not found at $ngenPath. Make sure .NET Framework is installed."
return
}
# Get a list of loaded assemblies
$assemblies = [AppDomain]::CurrentDomain.GetAssemblies()
# Filter assemblies based on the provided filter
$filteredAssemblies = $assemblies | Where-Object { $_.FullName -ilike "$assemblyFilter*" }
if ($filteredAssemblies.Count -eq 0) {
Write-Host "No matching assemblies found for optimization."
return
}
foreach ($assembly in $filteredAssemblies) {
# Get the name of the assembly
$name = [System.IO.Path]::GetFileName($assembly.Location)
# Display progress
Write-Progress -Activity $activity -Status "Optimizing $name"
# Use Ngen to install the assembly
Start-Process -FilePath $ngenPath -ArgumentList "install `"$($assembly.Location)`"" -Wait -WindowStyle Hidden
}
Write-Host "Optimization complete."
} catch {
Write-Host "An error occurred: $_"
}
}
# Optimize PowerShell assemblies:
Optimize-Assemblies -assemblyFilter "Microsoft.PowerShell."
每个 Windows Ansible 模块都使用 PowerShell。此优化减少了 PowerShell 启动所需的时间,从而消除了每次调用时的开销。
此代码片段使用本地映像生成器 ngen,为 PowerShell 依赖的程序集预先创建本地映像。
修复虚拟机/云实例启动时 CPU 占用率高的问题
如果您正在创建用于生成实例的黄金映像,您可以通过在黄金映像创建过程中处理 ngen 队列来避免启动时附近出现破坏性的高 CPU 任务,如果您知道 CPU 类型在黄金映像构建过程和运行时之间不会改变。
将以下内容放置在您的 playbook 的末尾附近,同时考虑到可能导致本地映像失效的因素(请参阅 MSDN)。
- name: generate native .NET images for CPU
win_dotnet_ngen: