title: How to write generic code to get time taken by a method execution in c#
body: <p>I need to log time taken by various methods , code blocks in my enterprise server application
  I am using Stopwatch as of now , sample code what I've implemented is as below:</p>
  
  <pre><code>var sw = new Stopwatch();
  sw.Start();
  DoSomething();
  sw.Stop();
  logManager.LogInformation(String.Format("Time taken by DoSomething function is {0} ms.", sw.ElapsedMilliseconds));
  </code></pre>
  
  <p>I am writing like this at many places in many .cs files, I just wanted to reduce this manual work by writing one common method or extension for measuring time taken. For this I am thinking to Wrap my actual method with the time measuring method like:</p>
  
  <pre><code>long elapsedMilliseconds = ExecuteAndGetTimeTaken(this.DoSomething());
  </code></pre>
  
  <p>Or generic extension methods like </p>
  
  <pre><code>long elapsedMilliseconds = this.DoSomething().GetTimeTaken();
  </code></pre>
  
  <p>It will be great if the method log the message with time taken too e.g.</p>
  
  <pre><code>long elapsedMilliseconds = ExecuteAndGetTimeTaken(this.DoSomething(),logManager,message);
  </code></pre>
  
  <p>How to write common class / method or extensions to solve the purpose?</p>