测量 PowerShell 命令耗时(Measure-Command)
精确测量一条命令、一个管道或一段脚本在 PowerShell 里跑了多久。
把命令放进大括号:Measure-Command { 你的命令 },然后读返回的 TimeSpan(TotalSeconds/TotalMilliseconds)。
01命令
命令
$ Measure-Command { Get-ChildItem -Recurse -File } | Select-Object TotalSeconds02作用说明
Measure-Command 会执行一次脚本块并返回 TimeSpan 对象,其 TotalSeconds 和 TotalMilliseconds 属性就是耗时。注意被测命令自身的输出会被吞掉——你只能看到计时结果而看不到命令输出,这样测量更干净。要比较两种写法的快慢,建议各自多跑几次取平均,因为首次运行的 JIT 和缓存会影响单次结果。
03风险
!注意: 大括号里的命令会真实执行,别拿 Remove-Item 这类破坏性命令去"测速"。
04撤销
✓无需撤销——该命令不会改变持久状态。
05来源
- Measure-Command依据: Documents Measure-Command running a scriptblock and returning a TimeSpan with detailed properties like TotalMilliseconds and TotalSeconds.
- Measure-Command依据: Shows syntax examples of timing script blocks and notes that the command output is suppressed while timing.
最后验证: 2026-09-18 · 分类: 开发者