The Easiest Way to Measure Your Method’s Performance in C#

Поділитися
Вставка
  • Опубліковано 26 вер 2024

КОМЕНТАРІ • 109

  • @rxuhwxx4tmly9xvcktcn2znpsx4
    @rxuhwxx4tmly9xvcktcn2znpsx4 Рік тому +80

    In regard to telemetry, I'd love to see an OpenTelemetry video. Aside from logs, both the traces and metrics SDKs are stable.

    • @nickchapsas
      @nickchapsas  Рік тому +61

      It is definitely coming

    • @silkfire
      @silkfire Рік тому +3

      Cool password bro

    • @slowjocrow6451
      @slowjocrow6451 11 місяців тому

      ​@@nickchapsasYes pleeease! Would love an Open Telemetry video

  • @lordicemaniac
    @lordicemaniac Рік тому +8

    it is very nice solution, one thing that i would change is that you have to call that magic class MethodTimeLogger exactly same way, I would prefer some way of registering class that implements some interface with the package

  • @alfredoquintanalopez2265
    @alfredoquintanalopez2265 Рік тому +13

    It is a great library. I was always waiting for something like this to measure time, easy, clean, and beautiful. Thanks Nick!!!!!

  • @brookster7772
    @brookster7772 Рік тому +5

    Another strategy would be to create middleware that is added to the very beginning of the pipeline on the way in… record the time, perhaps even store it in the request object…. Call Next()… then record the time to get your elapsed time for the entire request. In addition, one of the strategies we did is fire off a Kafka message (event hub / service bus works) over time u have some excellent telemetry that can be monitored.! Then efficiently send an entire batch of request telemetry to a Kafka topic every second
    And finally, instead of making a network call for every request, we would buffer up a batch of messages…

    • @yunsha9986
      @yunsha9986 Рік тому

      I do the same with NServicebus. Really effective way to monitor queue times.

    • @ergis8004
      @ergis8004 Рік тому

      You said it first... :)

  • @MrGTFOplz
    @MrGTFOplz Рік тому

    Cheers Nick. This is super useful. We have stop watches everywhere and its kinda clunky. Definitely going to investigate this.

  • @techmentormaria
    @techmentormaria Рік тому

    Thank you, this helps so much when working on new projects!

  • @MrHandsy
    @MrHandsy Рік тому

    I fucking love both you and this nugget provider for making and showcasing such a useful tool!

  • @lucaweidmann8339
    @lucaweidmann8339 Рік тому

    Wow thanks, that's exactly what i needed right now!

  • @KvapuJanjalia
    @KvapuJanjalia Рік тому +14

    There's also Serilog Timings library; writes measurements to log.

    • @nickchapsas
      @nickchapsas  Рік тому +12

      It does but it is Serilog specific. You can plug any logging provider or metrics collector in this one which I prefer

  • @domportera
    @domportera Рік тому +4

    Amazing, thank you Nick and Simon, this is the easy mode benchmarking I needed to actually start profiling in depth. is this compiled out of release builds?

  • @muhamedkarajic
    @muhamedkarajic Рік тому +1

    Great video as always, thank you for the hard work.

  • @learnsoftwarearchitecture
    @learnsoftwarearchitecture Рік тому

    Thanks! It is a really nice library (and underrated, only several hundreds stars) :)

  • @FrancisGauthier2
    @FrancisGauthier2 Рік тому

    Great video Nick. Ive been looking for a better way to measure methods for a long time. Thanks for sharing!

  • @ehudpinhas8873
    @ehudpinhas8873 Рік тому

    Thanks for the free course and awesome work

  • @ayalamac
    @ayalamac 11 місяців тому +2

    Hey Nick, nice video. Aside from time performance, can I log the allocated memory by the method?

  • @dimitris470
    @dimitris470 Рік тому

    Very interesting. Symfony uses such data to show in their debug toolbar/panel/graph how much time each part of the framework takes. You can even group stuff together like all repositories and see how much time your db interaction takes, or your template compilation or whatever

  • @DevonLehmanJ
    @DevonLehmanJ Рік тому +2

    Content starts at 2:15

  • @claude4074
    @claude4074 Рік тому +4

    Why can't this be done with a Source Code Generator? Having to include Fody for IL weaving seems like both a heavy handed and an old fashioned approach.
    It is expected that all developers using Fody become a Patron on OpenCollective.

  • @arielunanue4354
    @arielunanue4354 Рік тому

    Great video. Yesterday I was searching for middleware to measure the performance of the endpoints but now I see it can be done quite easy with this package too

  • @rmichaeldeutsch
    @rmichaeldeutsch Рік тому +6

    Hey @Nick Chapsas, cool utility! Love how you're always sharing these neat little libraries I never would have heard of otherwise!
    One important question that comes to mind with the way this is implemented: what happens to the stack trace from methods that have this attribute? Will they still have the original method's name and class?

    • @nickchapsas
      @nickchapsas  Рік тому +3

      Yes! Basically all that code will be as if it was in the main method at compile time

  • @TheDuerden
    @TheDuerden Рік тому +1

    Nice, but currently, you can't update Git from Visual Studio while this is installed - had to do a restart and remove it to commit. I am sure it will be fixed in time and will be most useful to use.

  • @sherifmohamed5294
    @sherifmohamed5294 Рік тому +1

    Hi Nick, Thank you for the great video ,
    How does the Package work or How Can I make method attribute work as decorator ?

  • @JohnOliverAtHome
    @JohnOliverAtHome Рік тому

    I love Aspects. I've used PostSharp for many years, which I believe, uses Fody under the covers - although PostSharp is not free (commercially anyway). This is a great way of removing those cross cutting concerns from your logic code. One aspect I've used is for tracing stored procedure parameters with a single method attribute.

  • @RichardONeil
    @RichardONeil Рік тому

    Fantastic! Thanks!

  • @lubnamanzoor132
    @lubnamanzoor132 Рік тому

    good explaination

  • @omidsojoody
    @omidsojoody Рік тому +1

    I'm not suggest any IL Weavering type libraries at all, because it it has some unwnated side effects like mismatched stacktrace compare to actual production code and so on....

    • @Lactorioga
      @Lactorioga 9 місяців тому

      agree, especially if it create exception trap

  • @danielprows6416
    @danielprows6416 Рік тому

    I don't know how this could be mixed with OpenTelemetry spans, because the way your log method just gets the elapsed time means that even if you make your logger build the spans manually, and you set the span's start/end times, you would still lose the parent child relationship with your spans.
    You could definitely implement metrics, but the spans seem dubious.
    if the package let you run your own method to start the stopwatch in addition to the logging, then you could do spans.
    The other weavers i've looked at like MethodBoundaryAspect and MethodDecorator have issues weaving correctly into the IL of the async/await state machine.
    MethodBoundaryAspect you can do a task.continueWith, but that still screws up the parent/child relationship.

  • @rubberuk
    @rubberuk Рік тому +3

    Please do an Azure course.

    • @nickchapsas
      @nickchapsas  Рік тому +8

      Only if Azure sponsors it

    • @domportera
      @domportera Рік тому

      @@nickchapsas they'd be stupid not to tbh

    • @kfique
      @kfique Рік тому

      @@nickchapsas you should ask them to sponsor it, I'll love to see an Azure course!

  • @garcipat
    @garcipat Рік тому

    I wonder how would you write those values in a time series database if your applicacion has not too many users at the same time of course. To observe the behaviour over time of the application. To observe endpoints.

  • @RichardNatal
    @RichardNatal 4 місяці тому

    Is it compatible with AOT?

  • @nickwong9649
    @nickwong9649 Рік тому

    I don't quite understand the last part - how do you use the non-allocating way of time measurement with Fody still, since the use of StopWatch is completely controlled by Fody itself?

  • @kasozivincent8685
    @kasozivincent8685 11 місяців тому

    Hmmm cool stuff. Does AOP libraries use assembly weaving too to handle cross-cutting concerns?

  • @the_sweet_heaven
    @the_sweet_heaven Рік тому

    How did you go to the code that is converted to ??

  • @casperhansen826
    @casperhansen826 7 днів тому

    I never measure performance unless there the code is slow, and not even then measure the code, I just look at the code and change it for better performance

  • @HenrryPires
    @HenrryPires Рік тому

    Very good

  • @Petoj87
    @Petoj87 Рік тому +2

    I have been watching your content a long time, i have never used Raider it seems nice but what do the pencils/fence in the lower right corner do?

    • @LeMustache
      @LeMustache Рік тому +2

      They let you choose which issues rider highlights (only up to errors, only up to warnings, etc.) and control other visual hints like enabling/disabling inline information.

    • @Petoj87
      @Petoj87 Рік тому

      @@LeMustache thanks!

  • @logank.70
    @logank.70 Рік тому

    How does this compare to environments using interceptors? It felt pretty similar just without marking up the code with details about cross-cutting concerns. Just setting it up when you are defining your dependency map and that's it. I've been happy with it so far.

  • @mohamedchaabouni4477
    @mohamedchaabouni4477 Рік тому

    Hi Nick !

  • @rahulkjohny4377
    @rahulkjohny4377 Рік тому

    this is cool!

  • @davidserb1678
    @davidserb1678 Рік тому

    Very cool post!
    I have a question, please. You showed how to send a variable in the message, but is it possible to send an object property? For example this is my signature method:
    ```public async Task GetAllAppointments([FromQuery] GetAllAppointmentsQuery paginationQuery)```
    I want to send a property from the object like this: ```[Time("Retrieved {paginationQuery.PageSize} appointments.")]```
    This gives an error, and from what I read in the official docs of the library, it doesn't support referencing properties. Is there a workaround?

  • @andrejcacala8629
    @andrejcacala8629 Рік тому

    Hi @nickchapsas, are you still planning to make video how to join this nugget with some telemetry? Also I would like to know if is possible to get hierarchical view of call when method call another methods.

  • @29Aios
    @29Aios Рік тому

    Hmm, but how it worked ?
    How the code was changed based on an Attribute before the compilation ?
    I've checked IL, and there is a Stopwatch already injected. I think this is a big topic to explain, but advanced...

  • @hotasfireph
    @hotasfireph Рік тому

    Is there a posibility to have an instance of the MethodTimeLog and not a static one? I wanted to log all method in one log in every request. But since since the Log function is static, I can't do it. Is there any better way than this?

  • @eunantog
    @eunantog Рік тому

    does this work with a method that yields results into an IEnumerable output?

    • @nickchapsas
      @nickchapsas  Рік тому

      I have actually never tried that. I'd have to give it a go and see

  • @fmonteiropt
    @fmonteiropt Рік тому

    I've made my own class to get this, but this is another level ... thanks a lot.
    Another that I would like to have, is a Translation method that can also works with variables in between the text, any ideas?

    • @reikooters
      @reikooters Рік тому +2

      What you need is an i18n library (internationalization). How they work is you create what is basically a dictionary of keys (identifiers for phrases, e.g. "login.error.invalidPassword"), and then you specify a value which is specific to each language, optionally passing parameters to fill in the places where variables appear as you mentioned. I haven't used one for C# before, personally, I do this on the front end instead where all the language text is stored in a json file. From a quick search on github for a C# library though, if it was me I would maybe try TypealizR - from the readme, it looks like it works in the way I would expect, and was last updated yesterday, so means it's still maintained. But again I have not used it myself as I don't do this on the backend.

  • @antonmartyniuk
    @antonmartyniuk Рік тому

    Does grabbing and dealing with MethodIndo has any performance issues when using this library?

  • @BhavyaShah26
    @BhavyaShah26 Місяць тому

    The link in the description is no longer valid!

  • @vladstatnyk8104
    @vladstatnyk8104 Рік тому

    I think that datadog is doing the same things for you already out of the box

  • @EliasElMango
    @EliasElMango Рік тому

    Does this work with aot?

  • @void_star_void
    @void_star_void Рік тому

    Can't signup on the website as a new User, there is a problem with teachable

  • @Petoj87
    @Petoj87 Рік тому +4

    While Fody is a cool project they expect you to pay money for it, seems a bit counter intuitive for a open source project... so i don't know if i would use the project unless i must...

    • @Krokoklemmee
      @Krokoklemmee Рік тому

      unreal engine is also open-source, but they still expect you to pay for it. it's just a business-model.

    • @Kollegah9997
      @Kollegah9997 Рік тому

      Found the "use open source but never ever support the developers behind it" guy

    • @Kollegah9997
      @Kollegah9997 Рік тому

      Found the "use open source but never ever support the developers behind it" guy

    • @okmarshall
      @okmarshall Рік тому

      Open source != free.

    • @PanzerFaustFurious
      @PanzerFaustFurious Рік тому

      Open source is not necessary free

  • @R0ckyRocket
    @R0ckyRocket Рік тому

    can you export them to a dashboard in aws? because using app.metrics its very easy since in expose an api endpoint for metrics

    • @nickchapsas
      @nickchapsas  Рік тому

      Sure it is. You can plug in App Metrics, OpenTelemetry or whatever you want

  • @gideonharmse4270
    @gideonharmse4270 Рік тому

    I really want to buy your course, however £80.00 is too pricey when you live in SA

  • @carmineos
    @carmineos Рік тому

    is it possible to automatically log all the input parameters without having to specify their names in the TimeAttribute ctor? Or even take complex object and serialize them to json

    • @nickchapsas
      @nickchapsas  Рік тому

      Yeah absolutely. You can do that by accessing them in the MethodInfo object. They are just an array that you can loop

    • @carmineos
      @carmineos Рік тому

      @@nickchapsas i thought it was possible for params metadata, but can you even get the runtime value of them?

  • @alexmac513
    @alexmac513 Рік тому

    What looks like an !. operator made me double take. Is that null forgiving, but thats for method calls? Or are you using a pre release version of the compiler?

    • @nickchapsas
      @nickchapsas  Рік тому +1

      It’s just suppressing the null warning. It’s been there since C# 8 I’m pretty sure

    • @alexmac513
      @alexmac513 Рік тому

      ​@@nickchapsas Ah yes, they added all the warnings on reference intent. While I am on C# 10 I disabled that functionality as the code originates from dotnet rc1 and I don't have the time to fix so many warnings. Probably make it more reliable when I do though.

  • @codingwithgyver1637
    @codingwithgyver1637 Рік тому

    oh yeahh

  • @thorkmunch
    @thorkmunch Рік тому

    Damn just bought 2 courses and can't use the discount now

  • @berkanbilgin2287
    @berkanbilgin2287 6 місяців тому

    like if your playback settings are 0.5x to understand him

  • @TodPalin
    @TodPalin Рік тому

    Could have done with this two weeks ago. 🙄

  • @TechySpeaking
    @TechySpeaking Рік тому +1

    First

  • @nayanchoudhary4353
    @nayanchoudhary4353 Рік тому

    I just got rid of Fody in my projects.
    Code generation has to be better than that.

    • @nickchapsas
      @nickchapsas  Рік тому +1

      Fody is assembly weaving not code generation

    • @nayanchoudhary4353
      @nayanchoudhary4353 Рік тому +1

      @@nickchapsas You're right. But Fody interferes with build. It's super annoying. So i don't want it

  • @davidwhite2011
    @davidwhite2011 Рік тому +1

    Third!

  • @KasperDahlTangen
    @KasperDahlTangen Рік тому

    The C# team should add python-like decorators

  • @IldarIsm
    @IldarIsm 4 місяці тому

    This is not the video i have searched for, Google

  • @Papiertig0r
    @Papiertig0r Рік тому

    This was 9 lines. disappointing.

  • @richardarielcruzcespedes9455

    First comment

  • @deepakdagar_change_is_in
    @deepakdagar_change_is_in Рік тому

    Datadog now support OpenTelelerty. The way more powerful combination

  • @rmcgraw7943
    @rmcgraw7943 Місяць тому

    public class StopWatch : System.Diagnostics.Stopwatch
    {
    public StopWatch() : base(){}
    public TimeSpan CalculateDuration(Action a)
    {
    base.Reset();base.Start();a();base.Start();return base.Elapsed;
    }
    public (TimeSpan Duration, TResult Result) CalculateDuration(Func function)
    {
    TResult result=default;
    base.Reset();base.Start();result=function();base.Start();return (Duration: base.Elapsed, Result:result);
    }
    public (TimeSpan Duration, TResult Result) CalculateDuration(Func asyncFunction)
    {
    TResult result=default;
    base.Reset();base.Start();base.Start();Call().RunSynchronously();return (Duration: base.Elapsed, Result:result);
    async Task Call()
    {
    result=await asyncFunction();
    }
    }
    }

  • @metaltyphoon
    @metaltyphoon Рік тому +2

    Would it just be simpler to add the Prometheus library and now you have all that info on /metrics ?

  • @ps2goat297
    @ps2goat297 9 місяців тому

    Fody isn't free, it requires a mandatory donation matching the number of devs using the code base or something like that.

  • @aqkhana2002
    @aqkhana2002 Місяць тому

    i have notice in the end of video you said better to use telemetry, then why not let us know how to if that is the best practice

  • @ivcbusinesssystems6613
    @ivcbusinesssystems6613 Рік тому

    How much does Fody cost?

  • @GuildOfCalamity
    @GuildOfCalamity Рік тому

    Love these types of videos Nick!

  • @whatgoglikeno6120
    @whatgoglikeno6120 Рік тому +1

    Nick how do you find these small libraries? Maybe make a video on that topic? If you put in a solid amount of time, do you think it's worth for "non creator developers" to do the same or should we just wait for the video/article?
    I am pretty involved and up to date. I follow people on youtube, I check conference talks, I am checking newsletters/aggregators, I randomly look for articles and videos like "10 useful nuget packages".
    But I feel I could still do with way more "hey this exists, this is probably useful some time in the future" type of knowledge.