命令行十进制转十六进制及计时工具
1. PowerShell 方案
cmd /c PowerShell -Command "Write-Output ('{0:X}' -f %shi%)"或简化版:
PowerShell -Command "'{0:X}' -f %shi%"
PowerShell -Command "%shi%.ToString('X')"2. Python 方案
python -c "print(format(%shi%, 'X'))"输出不带 0x 前缀,大写十六进制。
其他格式控制:
# 小写输出
python -c "print(format(%shi%, 'x'))"
# 指定位数补零(4位)
python -c "print(format(%shi%, '04X'))"
# 带 0x 前缀
python -c "print(hex(%shi%))"3. 关于 %%i 和 %i 的区别
| 使用场景 | 变量语法 |
|---|---|
| CMD 命令行直接输入 | %i |
| 批处理文件 (.bat) | %%i |
示例:
CMD 命令行:
for %i in (255 16 100) do python -c "print(format(%i, 'X'))"批处理文件:
for %%i in (255 16 100) do python -c "print(format(%%i, 'X'))"二、命令执行计时工具
1. PowerShell Measure-Command
powershell -Command "Measure-Command { ping 127.0.0.1 -n 4 }"2. Python 计时脚本
创建 timer.py:
import subprocess
import sys
import time
start = time.time()
rc = subprocess.call(sys.argv[1:])
print(f"执行时间: {time.time() - start:.3f} 秒 (返回值: {rc})")3. 创建 timer.bat 快捷命令
在同目录下创建 timer.bat:
@echo off
python "%~dp0timer.py" %*%~dp0 的含义
| 变量 | 含义 | 示例 |
|---|---|---|
%0 | 当前批处理文件的完整路径 | C:\tools\timer.bat |
%~d0 | 驱动器号 | C: |
%~p0 | 路径(不含驱动器) | \tools\ |
%~dp0 | 驱动器号+路径 | C:\tools\ |
因此 "%~dp0timer.py" 会被解析为 C:\tools\timer.py,确保无论从哪个目录执行 timer.bat,都能正确找到同目录下的 timer.py。
%* 的含义
%* 表示所有传递给批处理文件的参数。
示例:
@echo off
echo 所有参数: %*执行 timer hello world 123 输出 所有参数: hello world 123。
4. 纯 CMD 计时脚本(不依赖外部程序)
@echo off
setlocal enabledelayedexpansion
set start=%time%
%*
set end=%time%
for /f "tokens=1-4 delims=:.," %%a in ("%start%") do (
set /a sh=100%%a%%100, sm=100%%b%%100, ss=100%%c%%100, s_ms=100%%d%%100
)
for /f "tokens=1-4 delims=:.," %%a in ("%end%") do (
set /a eh=100%%a%%100, em=100%%b%%100, es=100%%c%%100, e_ms=100%%d%%100
)
set /a ms=e_ms-s_ms, secs=es-ss, mins=em-sm, hours=eh-sh
if !ms! lss 0 set /a secs-=1, ms+=100
if !secs! lss 0 set /a mins-=1, secs+=60
if !mins! lss 0 set /a hours-=1, mins+=60
if !hours! lss 0 set /a hours+=24
set /a total=!hours!*3600+!mins!*60+!secs!
echo 执行时间: !hours!:%mins%:%secs%.!ms! (!total!.!ms!秒)三、性能实测数据
测试命令:
timer python -c "print(format(%shi%, 'X'))"
timer cmd /c PowerShell -Command "Write-Output ('{0:X}' -f %shi%)"| 方案 | 执行时间 | 说明 |
|---|---|---|
| Python | 0.068 秒 | 启动快,适合短命令 |
| PowerShell | 0.441 秒 | 启动慢,.NET 运行时加载开销大 |
Python 比 PowerShell 快约 6.5 倍。
性能原因分析
PowerShell 启动过程:
- 加载 .NET Framework 运行时
- 加载 PowerShell 核心模块
- 解析命令行参数
- 执行实际命令
- 清理和退出
Python 启动开销相对较小。
四、各方案对比总结
| 场景 | 推荐方案 | 理由 |
|---|---|---|
| 单次转换 | Python | 启动快 |
| 循环多次转换 | Python(循环内执行) | 减少进程创建开销 |
| 批量处理 | 纯 Python 脚本 | 一次启动处理全部 |
| 不在乎启动速度 | PowerShell | 功能更丰富 |
| 最快速启动 | CMD 内部命令 | 但精度较低 |
性能排序(从快到慢)
CMD 内部命令 > Python > PowerShell > cmd /c PowerShell
精度对比
| 方法 | 启动开销 | 精度 | 依赖 |
|---|---|---|---|
| 纯 CMD | ~1ms | ~10ms | 无 |
| Python | ~50ms | ~1ms | Python |
| PowerShell | ~400ms | ~1ms | Windows 7+ |