Tuesday, November 21, 2017

How to implement Matlab-like Tic() and Toc() functions in C#

Tic() and Toc() functions are quite handy in Matlab and here is how you can get something similar in C#


using System;
using System.Diagnostics;

namespace MyTools
{
    class Perform
    {
        static Stopwatch stopWatch;

        public static void Tic()
        {
            stopWatch = new Stopwatch();
            stopWatch.Start();

        }

        public static void Toc()
        {
            TimeSpan ts = stopWatch.Elapsed;

            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);

            // elapsed time since the last Tic()
            Console.WriteLine($"Elapsed time : {elapsedTime} ");

        }
    }
}


Now you can check the performance of your code with:



Perform.Tic();

// some code that takes some time to execute

Perform.Toc();



OR if you use the using static directive:


using static MyTools.Perform;

Tic();

// some code that takes some time to execute

Toc();



Happy programming!


Source:

No comments:

Post a Comment

Your comment will be visible after approval.