This repository has been archived on 2026-04-18. You can view files and clone it, but cannot push or open issues or pull requests.
Virtual-Memory-Demo/Assets/Scripts/Simulation/StatsCollector.cs

78 lines
2.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
namespace VMdemo.Simulation
{
public class StatsCollector
{
public int TotalAccess { get; private set; }
public int TlbHit { get; private set; }
public int PageTableHit { get; private set; }
public int PageFault { get; private set; }
public long TotalCost { get; private set; }
public double TlbHitRate => TotalAccess > 0 ? (double)TlbHit / TotalAccess : 0.0;
public double PageTableHitRate => TotalAccess > 0 ? (double)PageTableHit / TotalAccess : 0.0;
public double AvgCost => TotalAccess > 0 ? (double)TotalCost / TotalAccess : 0.0;
public void Reset()
{
TotalAccess = 0;
TlbHit = 0;
PageTableHit = 0;
PageFault = 0;
TotalCost = 0L;
}
public int CalculateCost(bool tlbHit, bool pageTableHit, bool pageFault, int pageFaultPenalty)
{
if (pageFaultPenalty <= 0)
{
throw new ArgumentOutOfRangeException(nameof(pageFaultPenalty), "pageFaultPenalty 必须是正整数。");
}
if (tlbHit)
{
return 1;
}
if (pageFault)
{
return 4 + pageFaultPenalty;
}
if (pageTableHit)
{
return 4;
}
throw new InvalidOperationException("访问结果无效TLB miss 时必须是页表命中或缺页之一。");
}
public void RecordAccess(bool tlbHit, bool pageTableHit, bool pageFault, int cost)
{
if (cost < 0)
{
throw new ArgumentOutOfRangeException(nameof(cost), "cost 不能为负数。");
}
TotalAccess++;
if (tlbHit)
{
TlbHit++;
}
if (pageTableHit)
{
PageTableHit++;
}
if (pageFault)
{
PageFault++;
}
TotalCost += cost;
}
}
}