0

I using C# and woundering if it possible to create a custom attribute that will measuring execution time of code.

I'll explain. Let's say that you have the class Task:

public class Task
{
    public void Run()
    {
        Do1();
        Do2();
        // ...
    }

    public void Do1()
    {
        // ...
        Thread.sleep(10); // Dummy
    }

    public void Do2()
    {
        // ...
        Thread.sleep(5); // Dummy
    }
}

And the main file:

public static void Main()
{
    Task task = new Task();
    task.Run();
}

Now, I running this code on my server and feel that its running too slow (then I expected). So I using my brand new attribute to measuring execution time - let's call it MeasuringTimeAttribute:

[MeasuringTime]
public void Run()
{
    // ...
}

When running the code again, I want it to generate a report that looks like this:

Run() - Took 15s
    Run().Do1() - Took 10s
    Run().Do2() - Took 5s

The basic idea is that it will measuring for my code even if I have more then 2 levels (like in this example). Also, no matter what code it's running on. All I have to do is to add the [MeasuringTime] attribute the entry-point function.

Is this possible? If yes, I will appreciate every tip I'll get in order to implement it.

No1Lives4Ever
  • 6,430
  • 19
  • 77
  • 140

1 Answers1

2

Attributes do not change the way your code is executed. You should implement this time measuring in your server code yourself, from scratch, using Stopwatch or any other native or 3rd party utilities.

It will also be very difficult to handle nested calls.

In general, it looks like you are reinventing the wheel - there is a sort of software called "profiler". It will profile the execution time, memory consumption and other characteristics of your code during runtime. For example, you can use JetBrains DotTrace.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • Hi, thanks for answering. I know the class `Stopwatch` and using it. This question is part of my "learning". I know that I can use ready-to-use profiler. Just wondering if it possible to create a mini-profiler myself. – No1Lives4Ever Jun 06 '18 at 10:04
  • @No1Lives4Ever Yes, of course. Just add a check to your server code before and after method execution: if there is such attribute - measure time and output it somewhere. How to do this depends on your server architecture. – Yeldar Kurmangaliyev Jun 06 '18 at 10:09
  • @No1Lives4Ever There should be some libraries around for "decorating" methods (so add some benchmarking code). https://github.com/pardeike/Harmony. Haven't ever used it... Or you could modify the compiled program with Fody to add the benchmark code. – xanatos Jun 06 '18 at 10:10