数据
{"str": "str","int": 1,"float": 1.1,"str_list": ["a", "b"],"dict": {"a": "a", "b": "b"}}
代码
Python
import jsonimport timestr_ = """{"str": "str","int": 1,"float": 1.1,"str_list": ["a", "b"],"dict": {"a": "a", "b": "b"}}"""start = time.clock()num = 10000000for i in range(num):_ = json.loads(str_)end = time.clock()print('num: %d, cost: %s ms' % (num, (end - start) * 1000))
Golang
package mainimport ("encoding/json""fmt""io""log""strings""time")func Benchmark(name string, times uint, do func()) {start := time.Now().UnixNano()var i uint = 0for ;i < times; i++ {do()}end := time.Now().UnixNano()fmt.Printf("run %s %d times, cost: %d ms\n", name, times, (end-start)/int64(time.Millisecond))}func parse() {const jsonStream = `{"str": "str","int": 1,"float": 1.1,"str_list": ["a", "b"],"dict": {"a": "a", "b": "b"}}`type Sub struct {A string `json:"a"`B string `json:"b"`}type Message struct {Str string `json:"str"`Int int `json:"int"`Float float32 `json:"float"`StrList []string `json:"str_list"`Sub Sub `json:"dict"`}var dec *json.Decoderdec = json.NewDecoder(strings.NewReader(jsonStream))for {var m Messageif err := dec.Decode(&m); err == io.EOF {break} else if err != nil {log.Fatal(err)}}}func main() {util.Benchmark("parse json", 10000000, parse)}
结果
| 语言 | decode 1000万次耗时 |
|---|---|
| Python | 39475 ms |
| Golang | 34513 ms |
Golang 相较于 Python,在 json decode 上有明显优势,肉眼观察发现 Golang 程序的 CPU 利用率比 Python 的要高。
