-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataToString.swift
238 lines (213 loc) · 6.93 KB
/
DataToString.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//
// StringCompare.swift
// Test performance of String comparison
//
// Created by David Jones (@djones6) on 16/11/2016
//
import Foundation
import Dispatch
// Determine how many concurrent blocks to schedule (user specified, or 10)
var CONCURRENCY:Int = 10
// Determines how many times to convert per block
var EFFORT:Int = 5000
// Test duration (milliseconds)
var TEST_DURATION:Int = 5000
// Data to be converted
var DATA:Data = Data("Banana".utf8)
// Method of conversion
var METHOD = 1
// Determines how many times each block should be dispatched before terminating
var NUM_LOOPS:Int = 9999999
// Debug
var DEBUG = false
func usage() {
print("Options are:")
print(" -c, --concurrency n: number of concurrent Dispatch blocks (default: \(CONCURRENCY))")
print(" -n, --num_loops n: no. of times to invoke each block (default: \(NUM_LOOPS))")
print(" -e, --effort n: no. of conversions to perform per block (default: \(EFFORT))")
print(" -t, --time n: maximum runtime of the test (in ms) (default: \(TEST_DURATION))")
print(" -s, --data s: String to be converted from Data to String (default: \(String(data: DATA, encoding: .utf8)!))")
print(" -m, --method n: method of conversion:")
print(" 1 = String(data: Data, encoding: .utf8)")
print(" 2 = assignment via Array.withUnsafeBytes")
print(" -d, --debug: print a lot of debugging output (default: \(DEBUG))")
exit(1)
}
// Parse an expected int value provided on the command line
func parseInt(param: String, value: String) -> Int {
if let userInput = Int(value) {
return userInput
} else {
print("Invalid value for \(param): '\(value)'")
exit(1)
}
}
// Parse command line options
var param:String? = nil
var remainingArgs = CommandLine.arguments.dropFirst(1)
for arg in remainingArgs {
if let _param = param {
param = nil
switch _param {
case "-c", "--concurrency":
CONCURRENCY = parseInt(param: _param, value: arg)
case "-e", "--effort":
EFFORT = parseInt(param: _param, value: arg)
case "-t", "--time":
TEST_DURATION = parseInt(param: _param, value: arg)
case "-s", "--string":
DATA = Data(arg.utf8)
case "-m", "--method":
METHOD = parseInt(param: _param, value: arg)
case "-n", "--num_loops":
NUM_LOOPS = parseInt(param: _param, value: arg)
default:
print("Invalid option '\(arg)'")
usage()
}
} else {
switch arg {
case "-c", "--concurrency", "-e", "--effort", "-t", "--time", "-s", "--string", "-n", "--num_loops", "-m", "--method":
param = arg
case "-d", "--debug":
DEBUG = true
case "-?", "-h", "--help", "--?":
usage()
default:
print("Invalid option '\(arg)'")
usage()
}
}
}
if (DEBUG) {
print("Concurrency: \(CONCURRENCY)")
print("Effort: \(EFFORT)")
print("Debug: \(DEBUG)")
}
var MAX_CONCURRENCY:Int = CONCURRENCY
// Separate data for each thread
var DATAS:[Data] = [Data]()
var STRINGS:[String] = [String]()
for _ in 1...MAX_CONCURRENCY {
let d = Data(String(data: DATA, encoding: .utf8)!.utf8)
DATAS.append(d)
let s = String(repeating: "a", count: DATA.count)
STRINGS.append(s)
}
// Create a queue to run blocks in parallel
let queue = DispatchQueue(label: "hello", attributes: .concurrent)
let group = DispatchGroup()
let lock = DispatchSemaphore(value: 1)
var completeLoops:Int = 0
var RUNNING = true
func makeString(data: Data) -> String {
let array = Array(data) + [0]
return array.withUnsafeBytes { rawBuffer in
guard let pointer = rawBuffer.baseAddress?.assumingMemoryBound(to: CChar.self) else { return nil }
return String(validatingUTF8: pointer)
} ?? ""
}
func makeStringB(data: Data) -> String {
let array = Array(data)
return array.withUnsafeBytes { rawBuffer in
guard let pointer = rawBuffer.baseAddress?.assumingMemoryBound(to: CChar.self) else { return nil }
return String(validatingUTF8: pointer)
} ?? ""
}
// Block to be scheduled
func code(block: Int, loops: Int) -> () -> Void {
return {
var string: String?
var nsstring: NSString?
let lSTRING = STRINGS[block-1]
let lDATA = DATAS[block-1]
switch METHOD {
case 1:
for _ in 1...EFFORT {
string = String(data: lDATA, encoding: .utf8)!
}
case 2:
for _ in 1...EFFORT {
string = makeString(data: lDATA)
}
case 3:
for _ in 1...EFFORT {
string = makeStringB(data: lDATA)
}
case 4:
// Cost of creating an NSString
for _ in 1...EFFORT {
nsstring = NSString(data: lDATA, encoding: String.Encoding.utf8.rawValue)
}
string = String._unconditionallyBridgeFromObjectiveC(nsstring)
case 5:
// Cost of bridging an NSString to String
nsstring = NSString(data: lDATA, encoding: String.Encoding.utf8.rawValue)
for _ in 1...EFFORT {
string = String._unconditionallyBridgeFromObjectiveC(nsstring)
}
case 6:
// Cost of creating an NSString and then bridging it to String
for _ in 1...EFFORT {
nsstring = NSString(string: lSTRING)
string = String._unconditionallyBridgeFromObjectiveC(nsstring)
}
default:
print("Error - unknown method \(METHOD)")
return
}
if DEBUG && loops == 1 {
print("Instance \(block) done")
print("Converted data: '\(string!)'")
}
// Update loop completion stats
queue.async(group: group) {
_ = lock.wait(timeout: .distantFuture)
completeLoops += 1
lock.signal()
}
if RUNNING && loops < NUM_LOOPS {
// Dispatch a new block to replace this one
queue.async(group: group, execute: code(block: block, loops: loops+1))
} else {
if DEBUG { print("Block \(block) completed \(loops) loops") }
}
}
}
// warmup
queue.async(group: group, execute: code(block: 1, loops: 1))
_ = group.wait(timeout: .now() + DispatchTimeInterval.milliseconds(1000)) // 1 second
RUNNING = false
_ = group.wait(timeout: .distantFuture) // allow final blocks to finish
if DEBUG { print("Warmup complete") }
for c in 1...MAX_CONCURRENCY {
CONCURRENCY = c
completeLoops = 0
RUNNING = true
if DEBUG {
print("Concurrency: \(CONCURRENCY), Effort: \(EFFORT), Loops: \(NUM_LOOPS), Time limit: \(TEST_DURATION)ms")
}
let startTime = Date()
// Queue the initial blocks
for i in 1...CONCURRENCY {
queue.async(group: group, execute: code(block: i, loops: 1))
}
// Go
_ = group.wait(timeout: .now() + DispatchTimeInterval.milliseconds(TEST_DURATION)) // 5 seconds
RUNNING = false
_ = group.wait(timeout: .distantFuture) // allow final blocks to finish
let elapsedTime = -startTime.timeIntervalSinceNow
let completedOps = completeLoops * EFFORT
var displayOps = Double(completedOps)
var opsUnit:NSString = "%.0f"
if completedOps > 100000000 {
displayOps = displayOps / 1000000
opsUnit = "%.2fm"
} else if completedOps > 100000 {
displayOps = displayOps / 1000
opsUnit = "%.2fk"
}
let opsPerSec = displayOps / elapsedTime
let output = String(format: "Concurrency %d: completed %d loops (\(opsUnit) ops) in %.2f seconds, \(opsUnit) ops/sec", CONCURRENCY, completeLoops, displayOps, elapsedTime, opsPerSec)
print("\(output)")
}