原始版本
仅贴出计算时间的核心代码
//每个时间间隔0.1s调用一次
func secondsToTimeString(seconds: Float) -> (String, Int, Int, Int, Int, Int) {
let temp = seconds
let seconds = Int(temp)
// 天数计算
let days = (seconds)/(24*3600);
//小时计算
let hours = (seconds)%(24*3600)/3600;
//分钟计算
let minutes = (seconds)%3600/60;
//秒计算
let second = (seconds)%60;
let timeString = String(format: "%lu天 %02lu:%02lu:%02lu", days, hours, minutes, second)
return (timeString, days, hours, minutes, second, Int((temp-Float(seconds))*10))
}
每次调用都需要重新计算时分秒,计算很频繁。CPU这样也太累了吧?于是我决定给它减减负。实际上大多数时间有些数字都不会变动。比如分钟60秒才会变一次,小时60分钟才会变一次。等等。
进化版本
定义如下属性:
var days: Int?;
//小时
var hours: Int?;
var hoursFlag: Bool = false
//分钟
var minutes: Int?
var minutesFlag: Bool = false
//秒
var second: Int?;
var secondFlag: Bool = false
//每个时间间隔0.1s调用一次
func secondsToTimeString2(seconds: Float) -> (Int, Int, Int, Int, Int) {
let temp = seconds
let seconds = Int(temp)
let minInterval = Int((temp-Float(seconds))*10)
if second == nil {
second = (seconds)%60
}
if minutes == nil {
minutes = (seconds)%3600/60
}
if hours == nil {
hours = (seconds)%(24*3600)/3600
}
if days == nil {
days = (seconds)/(24*3600)
return (days!, hours!, minutes!, second!, minInterval)
}
if minInterval == 9 {
secondFlag = true
if second == 0 {
second = 60
second! -= 1
} else {
second! -= 1
}
}
if second == 59 && secondFlag == true {
secondFlag = false
minutesFlag = true
if minutes == 0 {
minutes = 60
minutes! -= 1
} else {
minutes! -= 1
}
}
if minutes == 59 && minutesFlag == true {
minutesFlag = false
hoursFlag = true
if hours == 0 {
hours = 24
hours! -= 1
} else {
hours! -= 1
}
}
if hours == 23 && hoursFlag == true {
hoursFlag = false
if days != 0 {
days! -= 1
}
}
return (days!, hours!, minutes!, second!, minInterval)
}
代码变得复杂多了,你们觉得我是不是咸的蛋疼?哈哈哈,我就是这样追求极致的呀!
代码虽然多了很多,也花了我不少时间debug。但是改进后性能却提升了很多。