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
| package main
import ( "fmt" "time" )
func GetDegreeByViolence(price int) string {
if price >= 0 && price < 10 { return "L" } if price >= 10 && price < 20 { return "M" } if price >= 20 && price < 30 { return "H" }
return "N" }
type Item struct { left int right int Degree string }
var config = []*Item{ {0, 10, "L"}, {10, 20, "M"}, {20, 30, "H"}, }
func GetDegreeByBinary(price int) string { start, end := 0, len(config)-1 mid := (start + end) / 2 for start <= end { if price < config[mid].left { end = mid - 1 } else if price >= config[mid].right { start = mid + 1 } else { return config[mid].Degree } mid = (start + end) / 2 } return "N" }
var m = map[int]string{}
func init() { for i := 0; i <= 30; i++ { if i >= 0 && i < 10 { m[i] = "L" } if i >= 10 && i < 20 { m[i] = "M" } if i >= 20 && i < 30 { m[i] = "H" } else { m[i] = "N" } } }
func GetDegreeByHash(price int) string { v, ok := m[price] if !ok { return "N" } return v }
func main() { CalculateTime(GetDegreeByViolence, 25, "violence") CalculateTime(GetDegreeByBinary, 25, "Binary") CalculateTime(GetDegreeByHash, 25, "Hash") }
func CalculateTime(f func(int) string, price int, name string) { startTime := time.Now() for i := 0; i < 1000000; i++ { f(price) } fmt.Println(name, "1000时间为:", time.Now().Sub(startTime)) }
|