Created
August 17, 2017 09:14
-
-
Save Scooletz/5c53ec8fce7854023097ce4c5e0ec000 to your computer and use it in GitHub Desktop.
This gist provides a test showing that AverageTimer32 handles ticks greater than int.MaxValue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Tests | |
{ | |
using System; | |
using System.Diagnostics; | |
using System.Security; | |
using System.Threading; | |
using NUnit.Framework; | |
public class PerformanceCounterCategoryTest | |
{ | |
const string Category = "Test-Only"; | |
const string TimeCounterName = "Time"; | |
const string TimeCounterBaseName = "TimeBase"; | |
[Test] | |
public void Test() | |
{ | |
var ticks = GetMachineTicks(TimeSpan.FromHours(1)); | |
Assert.Greater(ticks, int.MaxValue); | |
var counterCreationCollection = new CounterCreationDataCollection(Counters); | |
try | |
{ | |
EnsureNotExist(); | |
PerformanceCounterCategory.Create( | |
Category, | |
"Test only performance counters", | |
PerformanceCounterCategoryType.MultiInstance, | |
counterCreationCollection); | |
var time = GetCounter(TimeCounterName); | |
var timeBase = GetCounter(TimeCounterBaseName); | |
for (var i = 0; i < 120; i++) | |
{ | |
time.IncrementBy(ticks); | |
timeBase.Increment(); | |
Thread.Sleep(TimeSpan.FromSeconds(1)); | |
} | |
EnsureNotExist(); | |
PerformanceCounter.CloseSharedResources(); | |
} | |
catch (Exception ex) when (ex is SecurityException || ex is UnauthorizedAccessException) | |
{ | |
throw new Exception("Execution requires elevated permissions", ex); | |
} | |
} | |
static PerformanceCounter GetCounter(string timeCounterName) | |
{ | |
return new PerformanceCounter(Category, timeCounterName, "1", false); | |
} | |
static long GetMachineTicks(TimeSpan d) | |
{ | |
return d.Ticks / TimeSpan.TicksPerSecond * Stopwatch.Frequency; | |
} | |
static void EnsureNotExist() | |
{ | |
if (PerformanceCounterCategory.Exists(Category)) | |
{ | |
PerformanceCounterCategory.Delete(Category); | |
} | |
} | |
static CounterCreationData[] Counters = | |
{ | |
new CounterCreationData(TimeCounterName, "The time it took to successfully process a message.", PerformanceCounterType.AverageTimer32), | |
new CounterCreationData(TimeCounterBaseName, "The time it took to successfully process a message.", PerformanceCounterType.AverageBase) | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment