• Stars
    star
    686
  • Rank 65,892 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created over 12 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Injects some very basic method timing code.

MethodTimer.Fody

Chat on Gitter NuGet Status

Injects some very basic method timing code.

See Milestones for release notes.

This is an add-in for Fody

It is expected that all developers using Fody become a Patron on OpenCollective. See Licensing/Patron FAQ for more information.

Usage

See also Fody usage.

NuGet installation

Install the MethodTimer.Fody NuGet package and update the Fody NuGet package:

PM> Install-Package Fody
PM> Install-Package MethodTimer.Fody

The Install-Package Fody is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.

Add to FodyWeavers.xml

Add <MethodTimer/> to FodyWeavers.xml

<Weavers>
  <MethodTimer/>
</Weavers>

Your Code

public class MyClass
{
    [Time]
    public void MyMethod()
    {
        //Some code u are curious how long it takes
        Console.WriteLine("Hello");
    }
}

What gets compiled without an Interceptor

public class MyClass
{
    public void MyMethod()
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            //Some code u are curious how long it takes
            Console.WriteLine("Hello");
        }
        finally
        {
            stopwatch.Stop();
            Trace.WriteLine("MyClass.MyMethod " + stopwatch.ElapsedMilliseconds + "ms");
        }
    }
}

What gets compiled with an Interceptor

If you want to handle the logging you can define a static class to intercept the logging.

The interceptor takes one of the two following forms.

Note: when both methods are available, the intercepter will prefer the TimeSpan overload.

Interceptor with elapsed duration as long (milliseconds)

public static class MethodTimeLogger
{
    public static void Log(MethodBase methodBase, long milliseconds, string message)
    {
        //Do some logging here
    }
}

Then this will be compiled

public class MyClass
{
    public void MyMethod()
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            //Some code u are curious how long it takes
            Console.WriteLine("Hello");
        }
        finally
        {
            stopwatch.Stop();
            MethodTimeLogger.Log(methodof(MyClass.MyMethod), stopwatch.ElapsedMilliseconds);
        }
    }
}

Interceptor with elapsed duration as TimeSpan

public static class MethodTimeLogger
{
    public static void Log(MethodBase methodBase, TimeSpan elapsed, string message)
    {
        //Do some logging here
    }
}

Then this will be compiled

public class MyClass
{
    public void MyMethod()
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            //Some code u are curious how long it takes
            Console.WriteLine("Hello");
        }
        finally
        {
            stopwatch.Stop();
            MethodTimeLogger.Log(methodof(MyClass.MyMethod), stopwatch.Elapsed);
        }
    }
}

Using parameters inside the logging

If you want to get the parameter values inside the logging, you can use a string format in the attribute definition.

public class MyClass
{
    [Time("File name: '{fileName}'")]
    public void MyMethod(string fileName)
    {
        //Some code u are curious how long it takes
        Console.WriteLine("Hello");
    }
}

Then this will be compiled

public class MyClass
{
    public void MyMethod(string fileName)
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            //Some code u are curious how long it takes
            Console.WriteLine("Hello");
        }
        finally
        {
            stopwatch.Stop();
            var message = string.Format("File name: '{0}'", fileName);
            MethodTimeLogger.Log(methodof(MyClass.MyMethod), stopwatch.ElapsedMilliseconds, message);
        }
    }
}

The following values are allowed:

  • Any parameter name (e.g. {fileName})
  • {this} (calls ToString() on the instance itself) - Note that this is not available on static methods, the weaver will throw an error if being used in a static method

Note 1: sub-properties are not (yet?) supported. Support Fody on OpenCollective and this might be implemented!

Note 2: this feature requires an updated Log method call with the definition below. If this method (with the message parameter) is not found, the weaver will raise an error.

public static void Log(MethodBase methodBase, long milliseconds, string message)

Whats in the NuGet

In addition to the actual weaving assembly the NuGet package will also add a file TimeAttribute.cs to the target project.

[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor,AllowMultiple = false)]
class TimeAttribute : Attribute
{
}

At compile time this attribute and all usages to it will be removed from the target assembly. If you want to re-use the class in a common assembly change the class from internal to public. This will result in the class not being removed at compile time.

Icon

Icon courtesy of The Noun Project

More Repositories

1

Fody

Extensible tool for weaving .net assemblies
C#
4,325
star
2

Costura

Embed references as resources
C#
2,383
star
3

PropertyChanged

Injects INotifyPropertyChanged code into properties at compile time
C#
1,885
star
4

NullGuard

Adds null argument checks to an assembly
C#
686
star
5

Home

The landing page for Fody repositories
C#
671
star
6

ConfigureAwait

Configure async code's ConfigureAwait at a global level
C#
444
star
7

MethodDecorator

Compile time decorator pattern via IL rewriting
C#
380
star
8

Anotar

Simplifies logging through a static class and some IL manipulation.
C#
262
star
9

Equals

Generate Equals, GetHashCode and operators methods from properties.
C#
111
star
10

AsyncErrorHandler

An extension for Fody to integrate error handling into async and TPL code
C#
104
star
11

FodyAddinSamples

A working sample for each Fody Addin
C#
95
star
12

ToString

Generate ToString method from public properties.
C#
82
star
13

Janitor

Simplifies the implementation of IDisposable
C#
76
star
14

Ionad

Replaces static method calls.
C#
68
star
15

InfoOf

Provides methodof, propertyof and fieldof equivalents of typeof .
C#
65
star
16

Virtuosity

Change all members to virtual as part of your build.
C#
61
star
17

PropertyChanging

Injects INotifyPropertyChanging code into properties at compile time.
C#
54
star
18

ExtraConstraints

Facilitates adding constraints for Enum and Delegate to types and methods.
C#
47
star
19

Visualize

Adds debugger attributes to help visualize objects.
C#
43
star
20

Caseless

Change string comparisons to be case insensitive.
C#
40
star
21

Resourcer

Simplifies reading embedded resources from an Assembly.
C#
37
star
22

LoadAssembliesOnStartup

Loads all the references on startup by actually using the types in the module initializer.
C#
36
star
23

Obsolete

Helps keep usages of ObsoleteAttribute consistent.
C#
32
star
24

EmptyConstructor

Adds an empty constructor to classes even if you have a non-empty one defined.
C#
29
star
25

Scalpel

Strips all testing code from an assembly
C#
27
star
26

AssertMessage

Add 'message' parameter to Assertions. Nunit, Mstest, Xunit is supported.
C#
22
star
27

Publicize

Converts non-public members to public hidden members
C#
12
star
28

UniversalAppSample

C#
7
star
29

.github

1
star