【发布时间】:2014-06-04 20:40:15
【问题描述】:
我已经编写了以下解析二进制文件的代码
Param(
[Parameter(Mandatory=$True)]
[string]$inputFilePath
)
function GetLengthFrom2Byte
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$bytes
)
if ($bytes.Length -ne 2)
{
echo "Parametro di Input non valido"
}
else
{
$lenByte = New-Object Byte[](2)
$lenByte[0] = $bytes[1]
$lenByte[1] = $bytes[0]
return [BitConverter]::ToUInt16($lenByte, 0)
}
}
try
{
if (!(Test-Path($inputFilePath)))
{
Throw "File di Input non valido: <{0}>" -f $inputFilePath
}
$inputStream = New-Object IO.FileStream($inputFilePath, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
$inputBinaryReader = New-Object IO.BinaryReader($inputStream)
while ($inputBinaryReader.PeekChar() -ne -1)
{
$AfpHeader = $inputBinaryReader.ReadByte()
if ($AfpHeader -ne 0x5A)
{
Throw "Errore nella struttura AFP. Byte 0x5A non trovato all' offset: <{0}>" -f $inputBinaryReader.BaseStream.Position
exit 8
}
$AfpLength = $inputBinaryReader.ReadBytes(2)
$recordLength = GetLengthFrom2Byte($AfpLength)
$inputBinaryReader.ReadBytes($recordLength - 2) > $null
}
echo "File AFP Validato"
}
catch [Exception]
{
echo "Errore: {0}" -f $error[0]
exit 8
}
finally
{
$inputBinaryReader.Dispose()
$inputStream.Dispose()
}
exit 0
我不想详细介绍二进制解析。 问题是 C# 中的相同函数需要大约 50 秒,而在 Powershell 中需要 11 分钟。
由于我使用的是相同的课程,我不知道为什么差距如此之大。 有什么方法可以提高 powershell 性能?
【问题讨论】:
-
到底是什么问题?
-
您明白吗,C# 是编译的,而 PowerShell 是解释的?
-
我们说的是每一个字节循环的 12 倍……对我来说似乎很合理。
-
如果问题是如何提高性能。使用
Add-Type命令创建的内联 C#。 -
做
Add-Type @'<define a static class here in C#>'@。然后从您的脚本中调用此类的静态方法。见get-help Add-Type,那里有一个例子。
标签: c# .net powershell scripting binaryfiles