XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.Json;
using XFESystem.Core;
using XFESystem.Desktop;
using XFESystem.Platform;

// Actual production CPU canvas and mapped-memory presenter. This host-memory
// benchmark is neither Windows shell performance nor physical scanout evidence.
if (args.Length != 1) throw new ArgumentException("Provide a new output JSON path.");
string output = Path.GetFullPath(args[0]);
if (File.Exists(output)) throw new IOException("Do not overwrite benchmark evidence.");
const int width = 3840, height = 2160, frames = 240, pitch = width * 4 + 128;
var cases = new List<object>();
foreach (string name in new[] { "raw-full-present", "pointer", "window-drag", "window-resize", "text-scroll", "text-typing", "menu" })
{
    Console.WriteLine("MEASURING " + name);
    cases.Add(Measure(name));
    GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
}
var report = new
{
    Kind = "XfeCpuDesktopRenderProbe", Passed = true,
    Scope = "Production desktop in Windows host memory; excludes scheduler, device mapping and physical scanout",
    PhysicalDisplayAcceptance = false, WindowsParityAcceptance = false,
    Width = width, Height = height, ScalePercent = 200, Frames = frames,
    TimestampFrequency = Stopwatch.Frequency,
    PlatformAssemblySha256 = Hash(typeof(CpuFramebufferCanvas).Assembly.Location),
    DesktopAssemblySha256 = Hash(typeof(DesktopSession).Assembly.Location),
    Cases = cases, FinishedUtc = DateTime.UtcNow
};
using (var file = new FileStream(output, FileMode.CreateNew, FileAccess.Write))
    JsonSerializer.Serialize(file, report, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(output);

unsafe object Measure(string name)
{
    nuint length = (nuint)(pitch * height + 64);
    byte* address = (byte*)NativeMemory.Alloc(length);
    if (address == null) throw new OutOfMemoryException();
    try
    {
        new Span<byte>(address, (int)length).Fill(0xA5);
        var presenter = new MemoryFramebufferPresenter(new((nuint)address, length - 64, width, height, pitch, 32, 0xFF0000, 0xFF00, 0xFF));
        long[] samples = new long[name == "raw-full-present" ? 48 : frames];
        long allocated;
        if (name == "raw-full-present")
        {
            var pixels = new int[width * height];
            for (int i = 0; i < pixels.Length; i++) pixels[i] = (i * 7919) & 0xFFFFFF;
            for (int i = 0; i < 8; i++) presenter.Present(pixels, new(0, 0, width, height));
            allocated = GC.GetAllocatedBytesForCurrentThread();
            for (int i = 0; i < samples.Length; i++)
            {
                long begin = Stopwatch.GetTimestamp();
                presenter.Present(pixels, new(0, 0, width, height));
                samples[i] = Stopwatch.GetTimestamp() - begin;
            }
        }
        else
        {
            long logicalMs = 0;
            var canvas = new CpuFramebufferCanvas(presenter, scalePercent: 200);
            var workspace = new MemoryWorkspace();
            string path = SystemPaths.Combine(SystemPaths.Documents, "Fluidity.txt");
            workspace.WriteText(path, string.Join('\n', Enumerable.Range(0, 3000).Select(i => $"{i:D4}  XFESystem deterministic text rendering fixture.")));
            var desktop = new DesktopSession(canvas, workspace, monotonicMilliseconds: () => logicalMs);
            var window = desktop.Open(DesktopApplication.Files);
            if (name is "text-scroll" or "text-typing") window = desktop.Open(DesktopApplication.Editor, path);
            desktop.Pointer(500, 300, false, timestampMs: logicalMs);
            desktop.Render();
            if (!desktop.LastFrameCompleted) throw new InvalidOperationException("Initial production frame was not presented.");
            int anchorX = window.Bounds.X, anchorY = window.Bounds.Y;
            if (name == "window-drag")
                desktop.Pointer(anchorX + 120, anchorY + 16, true, timestampMs: logicalMs);
            if (name == "window-resize")
                desktop.Pointer(anchorX + window.Bounds.Width - 2, anchorY + window.Bounds.Height - 2, true, timestampMs: logicalMs);
            void Step(int i)
            {
                logicalMs += 5;
                switch (name)
                {
                    case "pointer": desktop.Pointer(350 + i % 180, 600 + i % 70, false, timestampMs: logicalMs); break;
                    case "window-drag": desktop.Pointer(anchorX + 120 + i % 160, anchorY + 16 + i % 70, true, timestampMs: logicalMs); break;
                    case "window-resize": desktop.Pointer(anchorX + 680 + i % 80, anchorY + 420 + i % 60, true, timestampMs: logicalMs); break;
                    case "text-scroll": desktop.Pointer(window.Bounds.X + 150, window.Bounds.Y + 160, false, i % 30 < 15 ? -1 : 1, logicalMs); break;
                    case "text-typing": desktop.Key(DesktopKey.Character, (char)('a' + i % 26)); break;
                    case "menu": desktop.Key(DesktopKey.StartMenu); break;
                }
                desktop.AdvanceFeedback(logicalMs);
                desktop.Render();
                if (!desktop.LastFrameCompleted) throw new InvalidOperationException("Production frame was not completed: " + name);
            }
            for (int i = 0; i < 32; i++) Step(i);
            allocated = GC.GetAllocatedBytesForCurrentThread();
            for (int i = 0; i < samples.Length; i++)
            {
                long begin = Stopwatch.GetTimestamp(); Step(i + 32); samples[i] = Stopwatch.GetTimestamp() - begin;
            }
        }
        allocated = GC.GetAllocatedBytesForCurrentThread() - allocated;
        string pixelsHash = Convert.ToHexStringLower(SHA256.HashData(new ReadOnlySpan<byte>(address, pitch * height)));
        for (int y = 0; y < height; y++)
            foreach (byte value in new ReadOnlySpan<byte>(address + y * pitch + width * 4, 128))
                if (value != 0xA5) throw new InvalidOperationException("Pitch padding was overwritten.");
        foreach (byte value in new ReadOnlySpan<byte>(address + pitch * height, 64))
            if (value != 0xA5) throw new InvalidOperationException("The framebuffer guard was overwritten.");
        long[] ordered = (long[])samples.Clone(); Array.Sort(ordered);
        double Ms(long ticks) => ticks * 1000d / Stopwatch.Frequency;
        double P(double percentile) => Ms(ordered[Math.Clamp((int)Math.Ceiling(percentile * ordered.Length) - 1, 0, ordered.Length - 1)]);
        return new { Name = name, Samples = samples.Length, P50Ms = P(.50), P95Ms = P(.95), P99Ms = P(.99), MaximumMs = Ms(ordered[^1]),
            TotalMeasuredMs = samples.Sum(Ms), AllocatedBytes = allocated, ScanoutSha256 = pixelsHash,
            GuardBytesUnchanged = true, RawFrameTicks = samples };
    }
    finally { NativeMemory.Free(address); }
}
static string Hash(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));