Why does the For method of the Parallel class gets faster over time?

Viewed 55

I'm doing some testing to find out some duplicates in generated UUID numbers and I use different approaches to execute the calculation. These are multithreading, a normal for loop and the for method of the Parallel class. Multithreading is the clear winner, normal for loop the looser and the Parallel.For method gets faster over time. I've done 10 tests with the Parallel.For and it decreased from 18.08 seconds to 11.80 seconds. I'm always starting the project to perform one test at a time, so I believe it can't get stored in memory. And I didn't do anything else on my computer during the test.

These are the test results of the Parallel.For method:

1: 00:00:18.08
2: 00:00:17.04
3: 00:00:16.79
4: 00:00:15.15
5: 00:00:13.00
6: 00:00:12.69
7: 00:00:12.66
8: 00:00:12.54
9: 00:00:12.33
10: 00:00:11.80

Is there any logic explanation for this?

By the way here's the code if it's needed:

// In Main
Parallel.For(0, 10, i =>
            {
                TestForUUIDDuplicates(i + 1);
            });

static void TestForUUIDDuplicates(object loopIndex)
    {
        if (!(loopIndex is int))
        {
            throw new InvalidCastException();
        }

        var uuids = new List<string>();

        for (int i = 0; i < 1000000; i++)
        {
            if (i % 100000 == 0) System.Console.WriteLine("Reached {0} in loop {1}", i, loopIndex);

            uuids.Add(GenerateUUID());
        }

        System.Console.WriteLine("Finished adding UUIDs in loop {0}.", loopIndex);

        var duplicates = uuids
            .GroupBy(uuid => uuid)
            .SelectMany(group => group.Skip(1)).ToList();

        System.Console.WriteLine("Finished finding duplicates in loop {0}.", loopIndex);

        foreach (var duplicate in duplicates)
        {
            Console.WriteLine(duplicate);
        }

        if (duplicates.Count == 0)
        {
            Console.WriteLine("No duplicates found in loop {0}.", loopIndex);
        }
        else
        {
            _duplicates.AddRange(duplicates);
        }

        Console.WriteLine("Finished loop {0}", loopIndex);
    }

    private static string GenerateUUID()
    {
        // var ticks = DateTime.Now.Ticks;
        var ticks = DateTime.Now.Ticks;
        var guid = Guid.NewGuid().ToString();
        return ticks.ToString() + '-' + guid;
    }
0 Answers
Related