Skip to content

Instantly share code, notes, and snippets.

@andersio
Created July 16, 2017 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersio/b8cc3ba01cb738ca61ebd9be919c5a2f to your computer and use it in GitHub Desktop.
Save andersio/b8cc3ba01cb738ca61ebd9be919c5a2f to your computer and use it in GitHub Desktop.
import XCTest
private func _measure(times: UInt64 = 2_000_000, label: String = #function, _ action: (() -> UInt64) -> Void) {
var result: UInt64 = 0
var minResult: UInt64 = .max
for i in 0 ..< times {
var start: UInt64!
action {
start = mach_absolute_time()
return i
}
let end = mach_absolute_time()
let r = (end - start)
result += r
minResult = min(minResult, r)
}
var base = mach_timebase_info()
_ = withUnsafeMutablePointer(to: &base, mach_timebase_info)
let ns = (result / times) / UInt64(base.denom) * UInt64(base.numer)
let minNs = minResult / UInt64(base.denom) * UInt64(base.numer)
print("@\(label): avg \(ns) ns; min \(minNs) ns")
}
private func _measureAndStart(times: UInt64 = 2_000_000, label: String = #function, _ action: () -> Void) {
return _measure(times: times, label: label) { start in
_ = start()
action()
}
}
struct TestData: Codable {
enum Gender: String, Codable {
case male
case female
}
let firstName = "hello"
let lastName = "hello"
let gender = Gender.male
let email = "a@b.com"
let id = 123456
let preferredNetwork = 2
let avatarPath = "/avatar/123456"
var jsonObject: Any {
return ["firstName": firstName,
"lastName": lastName,
"gender": Gender.male.rawValue,
"email": email,
"id": id,
"preferredNetwork": preferredNetwork,
"avatarPath": avatarPath] as [String: Any]
}
}
class Test: XCTestCase {
func testMappable() {
_measureAndStart(times: 250_000) {
_ = try! JSONSerialization.data(withJSONObject: TestData().jsonObject, options: [])
}
}
func testCodable() {
_measureAndStart(times: 250_000) {
_ = try! JSONEncoder().encode(TestData())
}
}
func testMappableDec() {
let data = try! JSONSerialization.data(withJSONObject: TestData().jsonObject, options: [])
_measureAndStart(times: 250_000) {
_ = try! JSONSerialization.jsonObject(with: data, options: [])
}
}
func testCodableDec() {
let data = try! JSONEncoder().encode(TestData())
_measureAndStart(times: 250_000) {
_ = try! JSONDecoder().decode(TestData.self, from: data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment