Skip to content

Instantly share code, notes, and snippets.

@Schroedi
Last active July 29, 2022 12:54
Show Gist options
  • Save Schroedi/25742f76345c3baf25e1b335671d35ad to your computer and use it in GitHub Desktop.
Save Schroedi/25742f76345c3baf25e1b335671d35ad to your computer and use it in GitHub Desktop.
Time all Run methods in dpb and print if they take more than 100ms. Uses https://github.com/pardeike/Harmony
using System;
using System.Linq;
using DreamPoeBot.Loki.Bot;
using DreamPoeBot.Loki.Common;
using HarmonyLib;
namespace kekslib
{
public static partial class KeksTools
{
private static Harmony harmony = new Harmony("de.keksdev.dpb");
private class PatchTaskRun
{
public static void Prefix(ITask __instance, out PerformanceTimer __state)
{
__state = new PerformanceTimer($"{__instance.Name}.Run", triggerMs:100, dontPrint:false);
__state.Start();
}
public static void Postfix(PerformanceTimer __state)
{
__state.StopAndPrint();
}
}
public static void PatchRun()
{
// only patch once
var myOriginalMethods = harmony.GetPatchedMethods();
if (myOriginalMethods.Any())
return;
// Get all types that implement ITask
var instances = from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
where t.GetInterfaces().Contains(typeof(ITask))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as ITask;
foreach (var instance in instances)
{
var original = instance.GetType().GetMethod("Run");
var prefix = typeof(PatchTaskRun).GetMethod(nameof(PatchTaskRun.Prefix));
var postfix = typeof(PatchTaskRun).GetMethod(nameof(PatchTaskRun.Postfix));
harmony.Patch(original, new HarmonyMethod(prefix), new HarmonyMethod(postfix));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment