Skip to content

Instantly share code, notes, and snippets.

@takasek
Last active June 19, 2017 10:38
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 takasek/ce66ac98f2971eac58991644d7471ccd to your computer and use it in GitHub Desktop.
Save takasek/ce66ac98f2971eac58991644d7471ccd to your computer and use it in GitHub Desktop.
potatotips #41 (iOS/Android開発Tips共有会) - connpass https://potatotips.connpass.com/event/57585/ で使用したテストコードです。
//
// HashablePerformanceTests.swift
// HashableExampleTests
//
// Created by takasek on 2017/06/18.
// Copyright © 2017年 takasek. All rights reserved.
//
import XCTest
struct YMD: Hashable {
let year: Int
let month: Int
let day: Int
enum Key { case year, month, day, plusAll, xorAll, shiftAll, none }
let keyForHashValue: Key
var hashValue: Int {
switch keyForHashValue {
case .year: return year
case .month: return month
case .day: return day
case .plusAll: return year * 10000 + month * 100 + day
case .xorAll: return year ^ month ^ day
case .shiftAll: return year << 14 + month << 5 + day //ビットシフトしてユニークに
case .none: return 0
}
}
static func ==(lhs: YMD, rhs: YMD) -> Bool {
return lhs.year == rhs.year
&& lhs.month == rhs.month
&& lhs.day == rhs.day
}
}
func YMDを10年分Setに突っ込む(using key: YMD.Key) {
let cal = Calendar(identifier: .gregorian)
// 2000/1/1 から 2010/12/31 までの日付が処理対象
let firstDate = DateComponents(calendar: cal,
year: 2000, month: 1, day: 1).date!
let lastDate = DateComponents(calendar: cal,
year: 2010, month: 12, day: 31).date!
var ymds: Set<YMD> = Set(minimumCapacity: 12)
var cursor = firstDate
while cursor < lastDate {
//カーソルが示すYMDをSetに入れる
ymds.insert(YMD(
year: cal.component(.year, from: cursor),
month: cal.component(.month, from: cursor),
day: cal.component(.day, from: cursor),
keyForHashValue: key
))
//カーソルを一日進める
cursor = cal.date(byAdding: .day, value: 1, to: cursor)!
}
}
class HashablePerformanceTests: XCTestCase {
func test_ハッシュ値がyear() {
self.measure {
YMDを10年分Setに突っ込む(using: .year)
}
}
func test_ハッシュ値がmonth() {
self.measure {
YMDを10年分Setに突っ込む(using: .month)
}
}
func test_ハッシュ値がday() {
self.measure {
YMDを10年分Setに突っ込む(using: .day)
}
}
func test_ハッシュ値がYYYYMMDD() {
self.measure {
YMDを10年分Setに突っ込む(using: .plusAll)
}
}
func test_ハッシュ値がY_xor_M_xor_D() {
self.measure {
YMDを10年分Setに突っ込む(using: .xorAll)
}
}
func test_ハッシュ値がbitshiftしてユニーク() {
self.measure {
YMDを10年分Setに突っ込む(using: .shiftAll)
}
}
func test_ハッシュ値が常に0() {
self.measure {
YMDを10年分Setに突っ込む(using: .none)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment