Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created April 2, 2019 07:34
Show Gist options
  • Save imzjy/9277e44046bd22765e73819d506c7f0b to your computer and use it in GitHub Desktop.
Save imzjy/9277e44046bd22765e73819d506c7f0b to your computer and use it in GitHub Desktop.
One file (few lines) implement for performance check. for C# / .NET
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace Dev.Lib
{
public static class Performance
{
public static T Check<T>(string name, Func<T> func, long expectedInMs = 500)
{
try
{
// Run the benchmark.
Stopwatch watch = Stopwatch.StartNew();
T result = func.Invoke();
watch.Stop();
// Output results.
var elapsedMilliseconds = watch.ElapsedMilliseconds;
if (elapsedMilliseconds > expectedInMs)
{
Log.Warn($"Performance Issue on '{name}, Expected:{ expectedInMs }ms, Actual: { elapsedMilliseconds }ms.");
}
return result;
}
catch (Exception)
{
Log.Error($"Performace Check '{name}' failed");
throw;
}
}
public static void Check(string name, Action action, long expectedInMs = 500)
{
try
{
// Run the benchmark.
Stopwatch watch = Stopwatch.StartNew();
action.Invoke();
watch.Stop();
// Output results.
var elapsedMilliseconds = watch.ElapsedMilliseconds;
if (elapsedMilliseconds > expectedInMs)
{
Log.Warn($"Performance Issue on '{name}, Expected:{ expectedInMs }ms, Actual:{ elapsedMilliseconds }ms.");
}
}
catch (Exception)
{
Log.Error($"Performace Check '{name}' failed");
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment