Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created April 2, 2019 07:34
Show Gist options
  • Select an option

  • Save imzjy/9277e44046bd22765e73819d506c7f0b to your computer and use it in GitHub Desktop.

Select an option

Save imzjy/9277e44046bd22765e73819d506c7f0b to your computer and use it in GitHub Desktop.

Revisions

  1. imzjy created this gist Apr 2, 2019.
    60 changes: 60 additions & 0 deletions Performance.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    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;
    }
    }
    }
    }