//: Playground - noun: a place where people can play
//import UIKit
import Foundation
var str = "Hello, playground"
let MAX = 100//_000
let testValues = Array(count:MAX, repeatedValue:2)
var total = 0
struct runTest {
var myName:String
let myFunc:Void -> Void
var startTime=0.0,interval=0.0
init(sign:String, f:(Void) -> Void) {
self.myName = sign
self.myFunc = f
}
mutating func reset() {
total = 0
self.startTime = currentTime()
}
func currentTime() -> Double {
return ((CFAbsoluteTimeGetCurrent() as Double) * 1000.0)
}
mutating func letUsLoopin() {
reset()
self.myFunc()
self.interval += currentTime() - startTime
}
}
func test01() {
for i in 0 ..< testValues.count {
total += testValues[i]
}
}
func test02() {
let max = testValues.count - 1
for i in 0...max {
total += testValues[i]
}
}
func test03() {
for v in testValues {
total += v
}
}
func test04() {
var test = testValues.count - 1
while test > 0 {
total += testValues[test]
test -= 1
}
}
// 実行関数配列
var runArray :[runTest] = [runTest(sign:"closed for",
f: test01),
runTest(sign:"opened for",
f: test02),
runTest(sign:"zipIndexing",
f: {for (index,v) in testValues.enumerate() {
total += v
}
}),
runTest(sign: "for-in",
f: test03),
runTest(sign: "while",
f: test04)
]
// 実行時間記録
var runTimes = [Double](count:runArray.count, repeatedValue:0.0)
let trialTimes = 1_000_000
for i in 0 ..< trialTimes {
let idx = i % runArray.count
runArray[idx].letUsLoopin()
}
for x in runArray {
print("\"\(x.myName)\" : \(x.interval)," )
}
// struct
// closed for : 59406.6962890625
// opened for : 59429.0154418945
// zipIndexing : 59891.3329467773
// for-in : 59426.2610473633
// class