Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pr/fix telemetry memcpy #53

Merged
merged 2 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased] - yyyy-mm-dd

### Added

- Added RcCircularBuffer<T> [@ikpil](https://github.com/ikpil)

### Fixed

### Changed
- Added DtPathCorridor.Init(int maxPath) function to allow setting the maximum path [@ikpil](https://github.com/ikpil)
- Changed DtPathCorridor.Init(int maxPath) function to allow setting the maximum path [@ikpil](https://github.com/ikpil)
- Changed from List<T> to RcCyclicBuffer in DtCrowdTelemetry execution timing sampling [@wrenge](https://github.com/wrenge)

### Removed

Expand Down
244 changes: 244 additions & 0 deletions src/DotRecast.Core/Buffers/RcCyclicBuffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
using System;
using System.Collections.Generic;
using System.Net.Security;

namespace DotRecast.Core.Buffers
{
// https://github.com/joaoportela/CircularBuffer-CSharp/blob/master/CircularBuffer/CircularBuffer.cs
public class RcCyclicBuffer<T>
{
private readonly T[] _buffer;

private int _start;
private int _end;
private int _size;

public RcCyclicBuffer(int capacity)
: this(capacity, new T[] { })
{
}

public RcCyclicBuffer(int capacity, T[] items)
{
if (capacity < 1)
{
throw new ArgumentException("RcCyclicBuffer cannot have negative or zero capacity.", nameof(capacity));
}

if (items == null)
{
throw new ArgumentNullException(nameof(items));
}

if (items.Length > capacity)
{
throw new ArgumentException("Too many items to fit RcCyclicBuffer", nameof(items));
}

_buffer = new T[capacity];

Array.Copy(items, _buffer, items.Length);
_size = items.Length;

_start = 0;
_end = _size == capacity ? 0 : _size;
}

public int Capacity => _buffer.Length;
public bool IsFull => Size == Capacity;
public bool IsEmpty => Size == 0;

public int Size => _size;

public T Front()
{
ThrowIfEmpty();
return _buffer[_start];
}

public T Back()
{
ThrowIfEmpty();
return _buffer[(_end != 0 ? _end : Capacity) - 1];
}

public T this[int index]
{
get
{
if (IsEmpty)
{
throw new IndexOutOfRangeException($"Cannot access index {index}. Buffer is empty");
}

if (index >= _size)
{
throw new IndexOutOfRangeException($"Cannot access index {index}. Buffer size is {_size}");
}

int actualIndex = InternalIndex(index);
return _buffer[actualIndex];
}
set
{
if (IsEmpty)
{
throw new IndexOutOfRangeException($"Cannot access index {index}. Buffer is empty");
}

if (index >= _size)
{
throw new IndexOutOfRangeException($"Cannot access index {index}. Buffer size is {_size}");
}

int actualIndex = InternalIndex(index);
_buffer[actualIndex] = value;
}
}

public void PushBack(T item)
{
if (IsFull)
{
_buffer[_end] = item;
Increment(ref _end);
_start = _end;
}
else
{
_buffer[_end] = item;
Increment(ref _end);
++_size;
}
}

public void PushFront(T item)
{
if (IsFull)
{
Decrement(ref _start);
_end = _start;
_buffer[_start] = item;
}
else
{
Decrement(ref _start);
_buffer[_start] = item;
++_size;
}
}

public void PopBack()
{
ThrowIfEmpty("Cannot take elements from an empty buffer.");
Decrement(ref _end);
_buffer[_end] = default(T);
--_size;
}

public void PopFront()
{
ThrowIfEmpty("Cannot take elements from an empty buffer.");
_buffer[_start] = default(T);
Increment(ref _start);
--_size;
}

public void Clear()
{
// to clear we just reset everything.
_start = 0;
_end = 0;
_size = 0;
Array.Clear(_buffer, 0, _buffer.Length);
}

public T[] ToArray()
{
int idx = 0;
T[] newArray = new T[Size];

ForEach(x => newArray[idx++] = x);

return newArray;
}

public void ForEach(Action<T> action)
{
var spanOne = ArrayOne();
foreach (var item in spanOne)
{
action.Invoke(item);
}

var spanTwo = ArrayTwo();
foreach (var item in spanTwo)
{
action.Invoke(item);
}
}

private void ThrowIfEmpty(string message = "Cannot access an empty buffer.")
{
if (IsEmpty)
{
throw new InvalidOperationException(message);
}
}

private void Increment(ref int index)
{
if (++index == Capacity)
{
index = 0;
}
}

private void Decrement(ref int index)
{
if (index == 0)
{
index = Capacity;
}

index--;
}

private int InternalIndex(int index)
{
return _start + (index < (Capacity - _start)
? index
: index - Capacity);
}

private Span<T> ArrayOne()
{
if (IsEmpty)
{
return new Span<T>(Array.Empty<T>());
}

if (_start < _end)
{
return new Span<T>(_buffer, _start, _end - _start);
}

return new Span<T>(_buffer, _start, _buffer.Length - _start);
}

private Span<T> ArrayTwo()
{
if (IsEmpty)
{
return new Span<T>(Array.Empty<T>());
}

if (_start < _end)
{
return new Span<T>(_buffer, _end, 0);
}

return new Span<T>(_buffer, 0, _end);
}
}
}
28 changes: 16 additions & 12 deletions src/DotRecast.Detour.Crowd/DtCrowdTelemetry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@ 3. This notice may not be removed or altered from any source distribution.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using DotRecast.Core;
using DotRecast.Core.Numerics;
using DotRecast.Core.Buffers;

namespace DotRecast.Detour.Crowd
{
Expand All @@ -34,7 +32,7 @@ public class DtCrowdTelemetry
private float _maxTimeToFindPath;

private readonly Dictionary<DtCrowdTimerLabel, long> _executionTimings = new Dictionary<DtCrowdTimerLabel, long>();
private readonly Dictionary<DtCrowdTimerLabel, List<long>> _executionTimingSamples = new Dictionary<DtCrowdTimerLabel, List<long>>();
private readonly Dictionary<DtCrowdTimerLabel, RcCyclicBuffer<long>> _executionTimingSamples = new Dictionary<DtCrowdTimerLabel, RcCyclicBuffer<long>>();

public float MaxTimeToEnqueueRequest()
{
Expand Down Expand Up @@ -85,19 +83,25 @@ private void Start(DtCrowdTimerLabel name)
private void Stop(DtCrowdTimerLabel name)
{
long duration = RcFrequency.Ticks - _executionTimings[name];
if (!_executionTimingSamples.TryGetValue(name, out var s))
if (!_executionTimingSamples.TryGetValue(name, out var cb))
{
s = new List<long>();
_executionTimingSamples.Add(name, s);
cb = new RcCyclicBuffer<long>(TIMING_SAMPLES);
_executionTimingSamples.Add(name, cb);
}

if (s.Count == TIMING_SAMPLES)
cb.PushBack(duration);
_executionTimings[name] = CalculateAverage(cb);
}

private static long CalculateAverage(RcCyclicBuffer<long> buffer)
{
long sum = 0L;
buffer.ForEach(item =>
{
s.RemoveAt(0);
}
sum += item;
});

s.Add(duration);
_executionTimings[name] = (long)s.Average();
return sum / buffer.Size;
}
}
}
Loading
Loading