Skip to content

Instantly share code, notes, and snippets.

@to11mtm
Last active November 17, 2021 02:04
Show Gist options
  • Save to11mtm/1c3f5137a207d59d5f3e61bb198aeeae to your computer and use it in GitHub Desktop.
Save to11mtm/1c3f5137a207d59d5f3e61bb198aeeae to your computer and use it in GitHub Desktop.
Napkin-level measuring of thread stats over a period of time
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ThreadStatGatherer : IDisposable
{
private List<int> ThreadStats = new List<int>();
private CancellationTokenSource runningCts = null;
private Thread runningThread = null;
private object _lockObj = new object();
public bool StartCollecting(TimeSpan interval)
{
lock (_lockObj)
{
if (runningThread != null)
{
return false;
}
var newCts = new CancellationTokenSource();
runningCts = newCts;
runningThread = new Thread(() =>
{
while (newCts.IsCancellationRequested == false)
{
Thread.Sleep(interval);
ThreadPool.GetAvailableThreads(out int aWt, out int aIOt);
ThreadPool.GetMaxThreads(out int maxWt, out int maxIOt);
ThreadStats.Add(maxWt - aWt);
}
});
runningThread.Start();
}
return true;
}
public void Clear()
{
ThreadStats.Clear();
}
public int GetMaxOverCollected()
{
return ThreadStats.Max();
}
public int GetAvg()
{
return (int)ThreadStats.Average();
}
public int GetMin()
{
return ThreadStats.Min();
}
public void StopCollecting()
{
runningCts.Cancel();
runningCts = null;
runningThread = null;
}
public void Dispose()
{
runningCts.Cancel();
runningThread = null;
runningCts = null;
}
//These are not a True percentile but get you a good idea where you're at.
public int Get95PercentileRough()
{
var totalCount = ThreadStats.Count;
return ThreadStats.OrderByDescending(ts=>ts).Skip((int)(totalCount*0.05)).FirstOrDefault();
}
public int Get50PercentileRough()
{
var totalCount = ThreadStats.Count;
return ThreadStats.OrderByDescending(ts => ts).Skip((int)(totalCount * 0.5)).FirstOrDefault();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment