| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace SKMC.Api.Common.Types
- {
- /// <summary>
- /// 包含时间戳的数据集
- /// </summary>
- public class TimestampSet
- {
- private readonly int capacity;
- private readonly (long Ticks, int Value)[] buffer;
- private int currentIndex;
- private long oldestTicks;
- private readonly object _lock = new object();
- public TimestampSet(int capacity)
- {
- this.capacity = capacity;
- buffer = new (long, int)[capacity];
- currentIndex = 0;
- oldestTicks = long.MaxValue;
- }
- /// <summary>
- /// 添加与时间戳相关的数据
- /// </summary>
- /// <param name="ticks"></param>
- /// <param name="value"></param>
- public void Add(long ticks, int value)
- {
- lock (_lock)
- {
- buffer[currentIndex] = (ticks, value);
- currentIndex = (currentIndex + 1) % capacity;
- if (currentIndex == 0)
- {
- oldestTicks = buffer[currentIndex].Ticks;
- }
- }
- }
- /// <summary>
- /// 添加当前"时间戳"的数据, 该"时间戳"为简化版: ticks/10000
- /// </summary>
- /// <param name="value"></param>
- public void Add(int value)
- {
- Add(DateTime.Now.Ticks / 10000, value);
- }
- /// <summary>
- /// 获取最新的一个数值
- /// </summary>
- /// <returns></returns>
- public int Take() => (currentIndex > 0) ? buffer[currentIndex - 1].Value : buffer[capacity - 1].Value;
- /// <summary>
- /// 获取某个时间戳之后的所有数据
- /// </summary>
- /// <param name="ticks">该"时间戳"为简化版: ticks/10000</param>
- /// <returns></returns>
- public List<int> GetDataAfter(long ticks)
- {
- List<int> result = new List<int>();
- lock (_lock)
- {
- for (int i = 0; i < capacity; i++)
- {
- var entry = buffer[i];
- if (entry.Ticks > ticks)
- {
- result.Add(entry.Value);
- }
- }
- }
- return result;
- }
- }
- }
|