Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Execution time of a Method

Tags:

c#

.net

I am making an Image Steganography project for my college. I have finished the project and have kept several different algorithms for hiding data in images.

What I want to ask is that is there any way in C# through which I can find the execution/running time between two points in a program. For example

//Some Code
//Code to start recording the time.
hideDataUsingAlgorithm();
//Code to stop recording and get the time of execution of the above function. 

I want to do this to show the difference between simple(less time consuming) and more efficient but time consuming algorithms (using same data and same image). I have around 10 different algorithms for Color and GrayScale Images.

There is no multithreading so that wont be a problem. Theres simply just one main Thread.

like image 233
user1589754 Avatar asked Apr 21 '13 10:04

user1589754


3 Answers

This is a useful extension method for Stopwatch:

public static class StopwatchExt
{
    public static string GetTimeString(this Stopwatch stopwatch, int numberofDigits = 1)
    {
        double time = stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
        if (time > 1)
            return Math.Round(time, numberofDigits) + " s";
        if (time > 1e-3)
            return Math.Round(1e3 * time, numberofDigits) + " ms";
        if (time > 1e-6)
            return Math.Round(1e6 * time, numberofDigits) + " µs";
        if (time > 1e-9)
            return Math.Round(1e9 * time, numberofDigits) + " ns";
        return stopwatch.ElapsedTicks + " ticks";
    }
}

Use it like this:

Stopwatch stopwatch = Stopwatch.StartNew();
//Call your method here
stopwatch.Stop();
Console.WriteLine(stopwatch.GetTimeString());
like image 131
Johan Larsson Avatar answered Oct 27 '22 14:10

Johan Larsson


System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.

See Also:

  1. Is DateTime.Now the best way to measure a function’s performance?
  2. High resolution timer in .NET
  3. Environment.TickCount vs DateTime.Now
  4. What’s the best way to benchmark programs in Windows?
like image 43
Obama Avatar answered Oct 27 '22 14:10

Obama


You can use StopWatch class:

var timer = System.Diagnostics.StopWatch.StartNew();
hideDataUsingAlgorithm();
timer.Stop();
var elapsed = timer.ElapsedMilliseconds;
like image 31
Zbigniew Avatar answered Oct 27 '22 15:10

Zbigniew