22 Aug

C# Calculate Execution Time

This example shows how much time takes a procedure/function/code. It is useful for micro-benchmarks in code optimization. To do this, We use the Stopwatch class in System.Diagnostics namespace.

Sample Code:

            // Create stopwatch
            Stopwatch stopwatch = new Stopwatch();

            // Begin timing
            stopwatch.Start();

            // Do something
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(10);
            }

            // Stop timing
            stopwatch.Stop();

            // Write result
            Console.WriteLine("Total Time: {0}", stopwatch.ElapsedMilliseconds);
14 Jul

C# Conditional Compilation Directives And Usage

The conditional compilation directives are used to conditionally include or exclude portions of a source file. This example shows how to use of preprocessor directives like “#define”, “#undef”, “#if”, etc. Firstly, you should add your variables above the “using”.

#define Debug // Debugging on
#undef  Trace // Tracing off
            #if Debug
                //To do something
            #endif

            #if Trace
                //To do someting    
            #endif