Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Grand Central Dispatch so fast? (For this Quicksort algorithm)

In an effort to brush up on some multithreading/sorting fun, I decided to put together a Quicksort test (written in Objective-C) that uses Grand Central Dispatch to determine how much faster it is to leverage multicore machines.

main.m

QuickSort.m

This is the output generated:

2011-11-27 13:10:55.595 Quicksort[1583:707] Took 4.731876 seconds to sort 1000000 elements with NO GCD
2011-11-27 13:10:55.670 Quicksort[1583:707] Took 0.070753 seconds to sort 1000000 elements WITH GCD

It's a fairly simple algorithm, using the Simple version mentioned on the Wikipedia page:

Quicksort on Wikipedia

I'm running this on an i7 machine, so would expect the performance increase to be on the order of 8x or so. Instead, the algorithm is approximately 60-70x faster when using Grand Central Dispatch.

Is the difference caused by a coding error on my part, or is there a technical advantage to using GCD that I'm just not aware of?

like image 741
Craig Otis Avatar asked Nov 27 '11 18:11

Craig Otis


People also ask

How does Grand Central Dispatch work?

GCD works by allowing specific tasks in a program that can be run in parallel to be queued up for execution and, depending on availability of processing resources, scheduling them to execute on any of the available processor cores (referred to as "routing" by Apple).

What is Grand Central Dispatch in iOS?

Dispatch, also known as Grand Central Dispatch (GCD), contains language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in macOS, iOS, watchOS, and tvOS.

What is GCD in Swift iOS?

Grand Central Dispatch (GCD) is a low-level API for managing concurrent operations. It can help improve your app's responsiveness by deferring computationally expensive tasks to the background. It's an easier concurrency model to work with than locks and threads.


1 Answers

You have got an error somewhere in your code, I changed the lines

    NSLog(@"Took %f seconds to sort %lu elements WITH GCD", duration, NUM_ELEMENTS);

to

    NSLog(@"Took %f seconds to sort %lu elements WITH GCD", duration, [sorted count]);

now the output is

2011-11-27 18:40:28.020 qs[37855:707] Took 5.412689 seconds to sort 1000000 elements with NO GCD
2011-11-27 18:40:28.104 qs[37855:707] Took 0.082455 seconds to sort 1 elements WITH GCD

Still investigating why however...

like image 84
joerick Avatar answered Oct 17 '22 01:10

joerick