Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Parallel Vs. Threaded code performance

I've been testing the performance of System.Threading.Parallel vs a Threading and I'm surprised to see Parallel taking longer to finish tasks than threading. I'm sure it's due to my limited knowledge of Parallel, which I just started reading up on.

I thought i'll share few snippets and if anyone can point out to me paralle code is running slower vs threaded code. Also tried to run the same comparison for finding prime numbers and found parallel code finishing much later than threaded code.

public class ThreadFactory
{
    int workersCount;
    private List<Thread> threads = new List<Thread>();

    public ThreadFactory(int threadCount, int workCount, Action<int, int, string> action)
    {
        workersCount = threadCount;

        int totalWorkLoad = workCount;
        int workLoad = totalWorkLoad / workersCount;
        int extraLoad = totalWorkLoad % workersCount;

        for (int i = 0; i < workersCount; i++)
        {
            int min, max;
            if (i < (workersCount - 1))
            {
                min = (i * workLoad);
                max = ((i * workLoad) + workLoad - 1);
            }
            else
            {
                min = (i * workLoad);
                max = (i * workLoad) + (workLoad - 1 + extraLoad);
            }
            string name = "Working Thread#" + i; 

            Thread worker = new Thread(() => { action(min, max, name); });
            worker.Name = name;
            threads.Add(worker);
        }
    }

    public void StartWorking()
    {
        foreach (Thread thread in threads)
        {
            thread.Start();
        }

        foreach (Thread thread in threads)
        {
            thread.Join();
        }
    }
}

Here is the program:

Stopwatch watch = new Stopwatch();
watch.Start();
int path = 1;

List<int> numbers = new List<int>(Enumerable.Range(0, 10000));

if (path == 1)
{
    Parallel.ForEach(numbers, x =>
    {
        Console.WriteLine(x);
        Thread.Sleep(1);

    });
}
else
{
    ThreadFactory workers = new ThreadFactory(10, numbers.Count, (min, max, text) => {

        for (int i = min; i <= max; i++)
        {
            Console.WriteLine(numbers[i]);
            Thread.Sleep(1);
        }
    });

    workers.StartWorking();
}

watch.Stop();
Console.WriteLine(watch.Elapsed.TotalSeconds.ToString());

Console.ReadLine();

Update:

Taking Locking into consideration: I tried the following snippet. Again the same results, Parallel seems to finish much slower.

path = 1; cieling = 10000000;

    List<int> numbers = new List<int>();

    if (path == 1)
    {
        Parallel.For(0, cieling, x =>
        {
            lock (numbers)
            {
                numbers.Add(x);    
            }

        });
    }

    else
    {
        ThreadFactory workers = new ThreadFactory(10, cieling, (min, max, text) =>
        {

            for (int i = min; i <= max; i++)
            {
                lock (numbers)
                {
                    numbers.Add(i);    
                }                       

            }
        });

        workers.StartWorking();
    }

Update 2: Just a quick update that my machine has Quad Core Processor. So Parallel have 4 cores available.

like image 875
ace Avatar asked Aug 26 '10 06:08

ace


1 Answers

The comparison is not very fair in regard to Threading.Parallel. You tell your custom thread pool that it'll need 10 threads. Threading.Parallel does not know how much threads it will need so it tries to adapt at run-time taking into account such things as current CPU load and other things. Since the number of iterations in the test is small enough you can this number of threads adaption penalty. Providing the same hint for Threading.Parallel will make it run much faster:


int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMinThreads(10, completionPortThreads);

like image 93
Konstantin Oznobihin Avatar answered Oct 06 '22 19:10

Konstantin Oznobihin