Added examples, Added performance tests, Updated readme

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-11-03 16:51:37 +01:00
parent 3d259d363a
commit 9facb66ee8
44 changed files with 3295 additions and 32 deletions
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MessagePack" Version="3.1.12" />
<Compile Include="..\..\_PerfTesting.cs" Link="_PerfTesting.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,77 @@
// Writes and reads the workload shared with the PureBasic tests, see `../_Workload.pbi`.
// Uses the low-level MessagePackWriter/MessagePackReader from MessagePack-CSharp, pinned in the .csproj.
using System.Buffers;
using MessagePack;
const int TotalSize = 33_554_432;
foreach (int size in new[] { 8, 1024, 65536 })
{
int count = TotalSize / size;
string text = new string('a', size);
byte[] encoded = WriteStrings(text, count);
Perf.Run($"str-{size}-write", count, () => WriteStrings(text, count).Length);
Perf.Run($"str-{size}-read", count, () => ReadStrings(encoded, count));
}
foreach (int size in new[] { 1024, 1048576 })
{
int count = TotalSize / size;
byte[] data = new byte[size];
Array.Fill(data, (byte)0xAB);
byte[] output = new byte[size];
byte[] encoded = WriteBinaries(data, count);
Perf.Run($"bin-{size}-write", count, () => WriteBinaries(data, count).Length);
Perf.Run($"bin-{size}-read", count, () => ReadBinaries(encoded, count, output));
}
return 0;
static byte[] WriteStrings(string text, int count)
{
var buffer = new ArrayBufferWriter<byte>();
var writer = new MessagePackWriter(buffer);
for (int i = 0; i < count; i++)
{
writer.Write(text);
}
writer.Flush();
return buffer.WrittenSpan.ToArray();
}
static long ReadStrings(byte[] encoded, int count)
{
var reader = new MessagePackReader(encoded);
long total = 0;
for (int i = 0; i < count; i++)
{
total += reader.ReadString()!.Length;
}
return total;
}
static byte[] WriteBinaries(byte[] data, int count)
{
var buffer = new ArrayBufferWriter<byte>();
var writer = new MessagePackWriter(buffer);
for (int i = 0; i < count; i++)
{
writer.Write(data);
}
writer.Flush();
return buffer.WrittenSpan.ToArray();
}
// Copies each field into `output`, like the PureBasic test.
static long ReadBinaries(byte[] encoded, int count, byte[] output)
{
var reader = new MessagePackReader(encoded);
long total = 0;
for (int i = 0; i < count; i++)
{
var bytes = reader.ReadBytes()!.Value;
bytes.CopyTo(output);
total += bytes.Length;
}
return total;
}
+42
View File
@@ -0,0 +1,42 @@
# Writes and reads the workload shared with the PureBasic tests, see `_Workload.pbi`.
import sys
from pathlib import Path
import msgpack
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from _PerfTesting import run
TOTAL_SIZE = 33_554_432
def write(value, count):
packer = msgpack.Packer(autoreset=False)
pack = packer.pack
for _ in range(count):
pack(value)
return packer.bytes()
def read(encoded, count):
unpacker = msgpack.Unpacker(raw=False, max_buffer_size=len(encoded))
unpacker.feed(encoded)
unpack = unpacker.unpack
total = 0
for _ in range(count):
total += len(unpack())
return total
def run_scenarios(name, value):
count = TOTAL_SIZE // len(value)
encoded = write(value, count)
run(f"{name}-{len(value)}-write", count, lambda: len(write(value, count)))
run(f"{name}-{len(value)}-read", count, lambda: read(encoded, count))
for size in (8, 1024, 65536):
run_scenarios("str", "a" * size)
for size in (1024, 1048576):
run_scenarios("bin", b"\xab" * size)
@@ -0,0 +1,174 @@
EnableExplicit
XIncludeFile "../../Includes/MessagePack.pbi"
XIncludeFile "../_PerfTesting.pbi"
XIncludeFile "_Workload.pbi"
; Writes and reads the shared workload, see `_Workload.pbi`.
; Current size, number of fields and string encoding.
Global FieldSize.i
Global FieldCount.i
Global Encoding.i
; Data written in each field.
Global Text.s
Global *Data
; Encoded fields, prepared once for the read scenarios.
Global *Encoded
; Receives each binary field when reading.
Global *Output
; Returns the finalized buffer, which must be freed with `FreeMemory()`.
; The writer is big enough for all the fields, the reallocations are measured in "MassiveReadAmount".
Procedure.i EncodeStrings()
Protected *Writer = MsgPackCreate(FieldCount * (FieldSize * 2 + 5))
Protected *Buffer
Protected i.i
If Not *Writer
PerfFail("Failed to create the writer !")
EndIf
For i = 1 To FieldCount
PerfCheckWrite(MsgPackWriteString(*Writer, Text, Encoding))
Next
*Buffer = MsgPackFinalize(*Writer)
If Not *Buffer
PerfFail("Failed to finalize the writer !")
EndIf
ProcedureReturn *Buffer
EndProcedure
; Returns the finalized buffer, which must be freed with `FreeMemory()`.
Procedure.i EncodeBinaries()
Protected *Writer = MsgPackCreate(FieldCount * (FieldSize + 5))
Protected *Buffer
Protected i.i
If Not *Writer
PerfFail("Failed to create the writer !")
EndIf
For i = 1 To FieldCount
PerfCheckWrite(MsgPackWriteBinary(*Writer, *Data, FieldSize))
Next
*Buffer = MsgPackFinalize(*Writer)
If Not *Buffer
PerfFail("Failed to finalize the writer !")
EndIf
ProcedureReturn *Buffer
EndProcedure
Procedure.q BufferSizeAndFree(*Buffer)
Protected Size.q = MemorySize(*Buffer)
FreeMemory(*Buffer)
ProcedureReturn Size
EndProcedure
Procedure.q ScenarioStringWrite()
ProcedureReturn BufferSizeAndFree(EncodeStrings())
EndProcedure
Procedure.q ScenarioStringRead()
Protected *Reader = MsgPackWrapMsgBuffer(*Encoded, MemorySize(*Encoded))
Protected Total.q
Protected i.i
If Not *Reader
PerfFail("Failed to wrap the buffer !")
EndIf
For i = 1 To FieldCount
Total + Len(MsgPackReadString(*Reader, Encoding))
Next
; Failed reads don't move the offset, so a failure breaks the next reads too.
If MsgPackLastError(*Reader) <> #MsgPack_Error_Success
PerfFail("A read failed !")
EndIf
MsgPackFree(*Reader, #False)
ProcedureReturn Total
EndProcedure
Procedure.q ScenarioBinaryWrite()
ProcedureReturn BufferSizeAndFree(EncodeBinaries())
EndProcedure
Procedure.q ScenarioBinaryRead()
Protected *Reader = MsgPackWrapMsgBuffer(*Encoded, MemorySize(*Encoded))
Protected Total.q, BytesRead.q
Protected i.i
If Not *Reader
PerfFail("Failed to wrap the buffer !")
EndIf
For i = 1 To FieldCount
BytesRead = MsgPackReadBinary(*Reader, *Output, FieldSize)
If BytesRead = #MsgPack_InvalidSize
PerfFail("A read failed !")
EndIf
Total + BytesRead
Next
MsgPackFree(*Reader, #False)
ProcedureReturn Total
EndProcedure
Procedure RunStringScenarios(Size.i, StringEncoding.i, Name.s)
FieldSize = Size
FieldCount = #Perf_TotalSize / Size
Encoding = StringEncoding
Text = LSet("", Size, "a")
*Encoded = EncodeStrings()
PerfRun("pb", Name + "-" + Str(Size) + "-write", @ScenarioStringWrite(), FieldCount)
PerfRun("pb", Name + "-" + Str(Size) + "-read", @ScenarioStringRead(), FieldCount)
FreeMemory(*Encoded)
EndProcedure
Procedure RunBinaryScenarios(Size.i)
FieldSize = Size
FieldCount = #Perf_TotalSize / Size
*Data = AllocateMemory(Size)
*Output = AllocateMemory(Size)
If Not *Data Or Not *Output
PerfFail("Failed to allocate the buffers !")
EndIf
FillMemory(*Data, Size, $AB)
*Encoded = EncodeBinaries()
PerfRun("pb", "bin-" + Str(Size) + "-write", @ScenarioBinaryWrite(), FieldCount)
PerfRun("pb", "bin-" + Str(Size) + "-read", @ScenarioBinaryRead(), FieldCount)
FreeMemory(*Encoded)
FreeMemory(*Output)
FreeMemory(*Data)
EndProcedure
OpenConsole()
RunStringScenarios(8, #PB_UTF8, "str")
RunStringScenarios(1024, #PB_UTF8, "str")
RunStringScenarios(65536, #PB_UTF8, "str")
RunStringScenarios(1024, #PB_Unicode, "str-utf16")
RunBinaryScenarios(1024)
RunBinaryScenarios(1048576)
End 0
@@ -0,0 +1,18 @@
$ErrorActionPreference = "Stop"
# Shows the error instead of closing the window right away.
trap {
Write-Host $_ -ForegroundColor Red
Pause
exit 1
}
. (Join-Path $PSScriptRoot "..\_PerfTesting.ps1")
# Requires Python with the packages from 'PerfTests\requirements.txt', and the .NET 10 SDK.
$Rows = @(Invoke-PureBasicPerfTests $PSScriptRoot)
$Rows += Invoke-PythonPerfTest (Join-Path $PSScriptRoot "PerfPython.py")
$Rows += Invoke-DotNetPerfTest (Join-Path $PSScriptRoot "DotNet")
Show-PerfResults $Rows $PSScriptRoot
Pause
+14
View File
@@ -0,0 +1,14 @@
; Workload shared by every implementation in this folder, keep `PerfPython.py` and `DotNet/Program.cs` in sync.
;
; For each size, `#Perf_TotalSize / Size` fields of `Size` bytes are written, then read:
; * Strings of 8, 1024 and 65536 "a" characters, encoded as UTF-8.
; * Binaries of 1024 and 1048576 bytes set to `$AB`.
; The PureBasic test also writes and reads strings of 1024 characters as UTF-16, which the others don't support.
;
; Scenarios are named `str-<Size>-write`, `str-<Size>-read`, `bin-<Size>-write` and `bin-<Size>-read`.
; `NsPerOp` is the time per field.
;
; Write check: the encoded size.
; Read check: the total number of characters or bytes read.
#Perf_TotalSize = 33554432