C# .Net unsafe code and stackalloc

A demo of using unsafe code in a .Net application.

using System;

namespace CsharpUnsafeDemo
{
    class CsharpUnsafeExample
    {
        // Enable unsafe code in project settings
        static unsafe void Main()
        {
            const int length = 10;

            int* stack = stackalloc int[length];
            
            var currentVal = stack;
            
            for (var i = 0; i <= length; i++, currentVal++)
            {
                *currentVal = i;
            }
            
            for (var i = 0; i < length; i++)
            {
                Console.WriteLine(stack[i]);
            }

            Console.ReadKey();
        }
    }
}

Returns:

0
1
2
3
4
5
6
7
8
9

C# .Net foreach performance comparison Parallel vs Serial vs LINQ

More investigation into the use of parallel and serial loops, again more testing is required to determine conclusive results.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace CsharpParallelForeachDemo
{
    class CsharpParallelForeachExample
    {
        static void Main()
        {
            RunSerial();

            Console.WriteLine();

            RunParallel();

            Console.WriteLine();

            RunLinqSerial();
            
            Console.ReadKey();
        }

        static void RunParallel()
        {
            Console.WriteLine("Processing Parallel Foreach");

            var stopwatch = Stopwatch.StartNew();

            var myRange = Enumerable.Range(1, 1000000);

            Parallel.ForEach(myRange, range => { var result = range*range; });

            stopwatch.Stop();

            // Where FFFFFFF represents milliseconds format
            Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);
        }

        static void RunSerial()
        {
            Console.WriteLine("Processing Serial Foreach");

            var stopwatch = Stopwatch.StartNew();

            var myRange = Enumerable.Range(1, 1000000);

            foreach (var range in myRange)
            {
                var result = range * range;
            }
    
            stopwatch.Stop();

            // Where FFFFFFF represents milliseconds format
            Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);
        }

        static void RunLinqSerial()
        {
            Console.WriteLine("Processing Serial LINQ");

            var stopwatch = Stopwatch.StartNew();

            var myRange = Enumerable.Range(1, 1000000);

            foreach (var result in myRange.Select(range => range * range)){}

            stopwatch.Stop();

            // Where FFFFFFF represents milliseconds format
            Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);
        }
    }
}

Results:

Processing Serial Foreach
Time: 0099253

Processing Parallel Foreach
Time: 088159

Processing Serial LINQ
Time: 0336764

C# .Net LINQ, PLINQ and Parallel.For

Another look into the parallel execution and understanding how to achieve the most effective results, I’ll do some more experiments with this to see what works best.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace CsharpParallelForDemo
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Processing for loop with PLINQ..");
            Console.WriteLine();
            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                result = null;
            }

            Console.WriteLine();
            Console.WriteLine("Processing Parallel for loop with LINQ..");
            Console.WriteLine();

            Parallel.For(1, 5, (i) =>
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                result = null;
            });

            Console.WriteLine();
            Console.WriteLine("Processing Parallel for loop with PLINQ..");
            Console.WriteLine();

            Parallel.For(1, 5, (i) =>
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                result = null;
            });


            Console.ReadKey();
        }
    }
}

Returns:

Processing for loop with PLINQ..

Number of cores: 1 Time: 1022974
Number of cores: 2 Time: 0653203
Number of cores: 3 Time: 0719758
Number of cores: 4 Time: 0524761

Processing Parallel for loop with LINQ..

Number of cores: 2 Time: 0582022
Number of cores: 4 Time: 0644796
Number of cores: 3 Time: 0912731
Number of cores: 1 Time: 1034905

Processing Parallel for loop with PLINQ..

Number of cores: 3 Time: 0717623
Number of cores: 2 Time: 0978785
Number of cores: 4 Time: 0979141
Number of cores: 1 Time: 1378484

C# .Net what’s in the Environment class?

Thought this would be interesting to show what’s in the System.Environment class, the code below is just borrowed from the MSDN documentation with a few tidy ups. It’s useful to know what the Environment class provides.

using System;
using System.Collections;

namespace CsharpEnvironmentDemo
{
    class CsharpEnvironmentExample
    {
        static void Main()
        {
            var newLine = Environment.NewLine;
            Console.WriteLine();

            Console.WriteLine("Output from the Environment class:");
            Console.WriteLine();

            Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
            Console.WriteLine();

            var arguments = Environment.GetCommandLineArgs();
            Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
            Console.WriteLine();

            Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
            Console.WriteLine();

            Console.WriteLine("ExitCode: {0}", Environment.ExitCode);
            Console.WriteLine();

            Console.WriteLine("HasShutdownStarted: {0}", Environment.HasShutdownStarted);
            Console.WriteLine();

            Console.WriteLine("MachineName: {0}", Environment.MachineName);
            Console.WriteLine();

            Console.WriteLine("NewLine: {0}  first line{0}  second line{0}  third line",
                                  Environment.NewLine);
            Console.WriteLine();

            Console.WriteLine("OSVersion: {0}", Environment.OSVersion);
            Console.WriteLine();

            Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
            Console.WriteLine();

            Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
            Console.WriteLine();

            Console.WriteLine("TickCount: {0}", Environment.TickCount);
            Console.WriteLine();

            Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
            Console.WriteLine();

            Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
            Console.WriteLine();

            Console.WriteLine("UserName: {0}", Environment.UserName);
            Console.WriteLine();

            Console.WriteLine("Version: {0}", Environment.Version);
            Console.WriteLine();

            Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet);
            Console.WriteLine();

            const string query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";
            var str = Environment.ExpandEnvironmentVariables(query);

            Console.WriteLine("ExpandEnvironmentVariables: {0}  {1}", newLine, str);
            Console.WriteLine();

            Console.WriteLine("GetEnvironmentVariable: {0}  My temporary directory is {1}.", newLine,
                                   Environment.GetEnvironmentVariable("TEMP"));
            Console.WriteLine();

            Console.WriteLine("GetEnvironmentVariables: ");
            var environmentVariables = Environment.GetEnvironmentVariables();
            foreach (DictionaryEntry entry in environmentVariables)
                Console.WriteLine("  {0} = {1}", entry.Key, entry.Value);

            Console.WriteLine();

            Console.WriteLine("GetFolderPath: {0}",
                         Environment.GetFolderPath(Environment.SpecialFolder.System));
            Console.WriteLine();

            var drives = Environment.GetLogicalDrives();
            Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));

            Console.ReadKey();
        }
    }
}

.Net C# parallel Linq (PLINQ) and ToList() question

I took a question related to a previous post and about the use of ToList() in a PLINQ query, I put together a test that shows the quickest way to execute a call to ToList(). The results indicate that it’s much faster to call ToList() after LINQ execution.

using System;
using System.Diagnostics;
using System.Linq;

namespace CsharpParallelLinqExample
{
    class CsharpParallelLinqDemo
    {
        static void Main()
        {
            Console.WriteLine();

            Console.WriteLine("Processing and calling .ToList()");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                        .WithDegreeOfParallelism(i)
                        .Select(x => x).ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.WriteLine();

            Console.WriteLine("Processing and calling .ToList() after PLINQ execution");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.ReadKey();
        }
    }
}

Returns:

Processing and calling .ToList()
Number of cores: 1 Time: 102726
Number of cores: 2 Time: 0653831
Number of cores: 3 Time: 0599256
Number of cores: 4 Time: 0595193

Processing and calling .ToList() after PLINQ execution
Number of cores: 1 Time: 0917514
Number of cores: 2 Time: 0629758
Number of cores: 3 Time: 052276
Number of cores: 4 Time: 057208

C# .Net using the StopWatch() class to measure execution performance

The StopWatch class is a member of the System.Diagnostics namespace, it’s a really useful way to get some information on how long a block of code is taking to execute. To setup a timing session, this is how you do it.

using System.Diagnostics;
..
var stopwatch = Stopwatch.StartNew();
..
stopwatch.Stop();

// Where FFFFFFF represents milliseconds format
Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);

.Net C# parallel Linq (PLINQ) and degree of parallelism example

A quick demo to see how the degree of parallelism affects the execution speed of a simple Linq/PLINQ query. The results indicate that using PLINQ could be more efficient if the executing environment has multiple cores.

using System;
using System.Diagnostics;
using System.Linq;

namespace CsharpPLinqDemo
{
    class CsharpPLinqExample
    {
        static void Main()
        {
            for (var i = 1; i <= 1; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                Console.WriteLine("Processing..");

                var stopwatch = Stopwatch.StartNew();

                var result = myRange.Select(x => x);

                stopwatch.Stop();

                Console.WriteLine("Time: {0:FFFFFFF}", stopwatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.WriteLine();

            Console.WriteLine("Parallel Processing..");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                        .WithDegreeOfParallelism(i)
                        .Select(x => x);

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.WriteLine();

            Console.WriteLine("Processing and calling .ToList()");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x).ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }

            Console.WriteLine();

            Console.WriteLine("Processing and calling .ToList() after PLINQ execution");

            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                myRange = null;
                result = null;
            }


            Console.ReadKey();
        }
    }
}

Results:

Processing..
Time: 0026234

Parallel Processing..
Number of cores: 1 Time: 0025167
Number of cores: 2 Time: 0000022
Number of cores: 3 Time: 0000022
Number of cores: 4 Time: 0000019

Processing and calling .ToList()
Number of cores: 1 Time: 1007239
Number of cores: 2 Time: 0862795
Number of cores: 3 Time: 0785533
Number of cores: 4 Time: 0543469

Processing and calling .ToList() after PLINQ execution
Number of cores: 1 Time: 0890755
Number of cores: 2 Time: 0567519
Number of cores: 3 Time: 0545084
Number of cores: 4 Time: 0473126

.Net C# using the Implicit keyword

A simple program to demonstrate using the C# Implicit keyword.

using System;

namespace CsharpImplicitKeyWordDemo
{
    /// <summary>
    /// Class to demonstrate the C# Implicit operator
    /// </summary>
    public class CsharpImplicitKeyWordExample
    {
        static void Main()
        {
            var number = new Number(42);

            // Implicit Double 
            long longNumber = number;

            // Implicit Number 
            const int aNumber = 21;

            Console.WriteLine("{0} : {1}", longNumber, aNumber);

            Console.ReadLine();
        }
    }

    /// <summary>
    /// Class implementing the Implicit keyword.
    /// </summary>
    internal class Number
    {
        /// <summary>
        /// The _value
        /// </summary>
        private readonly long _value;

        /// <summary>
        /// Initializes a new instance of the <see cref="Number"/> class.
        /// </summary>
        /// <param name="number">The command.</param>
        public Number(long number)
        {
            _value = number;
        }

        /// <summary>
        /// Return a long number.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <returns>a Long</returns>
        public static implicit operator long(Number number)
        {
            return number._value;
        }

        /// <summary>
        /// Return the input as the Number type.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <returns>a Number</returns>
        public static implicit operator Number(long number)
        {
            return new Number(number);
        }
    }
}

Returns:

42 : 21