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: