Created
July 22, 2017 00:59
-
-
Save rxhanson/640edc1a8b9d0f1d624381231e94ac6a to your computer and use it in GitHub Desktop.
Playground demoed during threads in swift meetup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import Cocoa | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
//----------------------------------- | |
// Source: https://www.appcoda.com/grand-central-dispatch/ | |
func queuesWithQosExample() { | |
let queue1 = DispatchQueue(label: "com.example.myqueue", qos: .userInteractive) | |
let queue2 = DispatchQueue(label: "com.example.myqueue2", qos: .utility) | |
queue1.async { | |
for i in 0..<10 { | |
print("🔴", i) | |
} | |
} | |
queue2.async { | |
for i in 100..<110 { | |
print("🔵", i) | |
} | |
} | |
} | |
//queuesWithQosExample() | |
//----------------------------------- | |
// Source: https://www.appcoda.com/grand-central-dispatch/ | |
func concurrentQueuesExample() { | |
let queue = DispatchQueue(label: "com.example.myqueue", qos: .utility, attributes: .concurrent) | |
queue.async { | |
for i in 0..<10 { | |
print("🔴", i) | |
} | |
} | |
queue.async { | |
for i in 100..<110 { | |
print("🔵", i) | |
} | |
} | |
queue.async { | |
for i in 1000..<1010 { | |
print("⚫️", i) | |
} | |
} | |
} | |
//concurrentQueuesExample() | |
//----------------------------------- | |
// Source: Paul Hudson. “Hacking with macOS.” | |
func runMultiprocessing(useGCD: Bool) { | |
func fibonacci(of num: Int) -> Int { | |
if num < 2 { | |
return num | |
} else { | |
return fibonacci(of: num - 1) + fibonacci(of: num - 2) | |
} | |
} | |
var array = Array(0 ..< 24) | |
let start = CFAbsoluteTimeGetCurrent() | |
if useGCD { | |
DispatchQueue.concurrentPerform(iterations: array.count) { | |
array[$0] = fibonacci(of: $0) | |
} | |
} else { | |
for i in 0 ..< array.count { | |
array[i] = fibonacci(of: array[i]) | |
} | |
} | |
let end = CFAbsoluteTimeGetCurrent() - start | |
print("Took \(end) seconds") | |
} | |
//runMultiprocessing(useGCD: true) | |
//runMultiprocessing(useGCD: false) | |
//----------------------------------- | |
sleep(3) | |
PlaygroundPage.current.finishExecution() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment