数据

  1. {
  2. "str": "str",
  3. "int": 1,
  4. "float": 1.1,
  5. "str_list": ["a", "b"],
  6. "dict": {"a": "a", "b": "b"}
  7. }

代码

Python

  1. import json
  2. import time
  3. str_ = """{
  4. "str": "str",
  5. "int": 1,
  6. "float": 1.1,
  7. "str_list": ["a", "b"],
  8. "dict": {"a": "a", "b": "b"}
  9. }"""
  10. start = time.clock()
  11. num = 10000000
  12. for i in range(num):
  13. _ = json.loads(str_)
  14. end = time.clock()
  15. print('num: %d, cost: %s ms' % (num, (end - start) * 1000))

Golang

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "strings"
  8. "time"
  9. )
  10. func Benchmark(name string, times uint, do func()) {
  11. start := time.Now().UnixNano()
  12. var i uint = 0
  13. for ;i < times; i++ {
  14. do()
  15. }
  16. end := time.Now().UnixNano()
  17. fmt.Printf("run %s %d times, cost: %d ms\n", name, times, (end-start)/int64(time.Millisecond))
  18. }
  19. func parse() {
  20. const jsonStream = `
  21. {
  22. "str": "str",
  23. "int": 1,
  24. "float": 1.1,
  25. "str_list": ["a", "b"],
  26. "dict": {"a": "a", "b": "b"}
  27. }
  28. `
  29. type Sub struct {
  30. A string `json:"a"`
  31. B string `json:"b"`
  32. }
  33. type Message struct {
  34. Str string `json:"str"`
  35. Int int `json:"int"`
  36. Float float32 `json:"float"`
  37. StrList []string `json:"str_list"`
  38. Sub Sub `json:"dict"`
  39. }
  40. var dec *json.Decoder
  41. dec = json.NewDecoder(strings.NewReader(jsonStream))
  42. for {
  43. var m Message
  44. if err := dec.Decode(&m); err == io.EOF {
  45. break
  46. } else if err != nil {
  47. log.Fatal(err)
  48. }
  49. }
  50. }
  51. func main() {
  52. util.Benchmark("parse json", 10000000, parse)
  53. }

结果

语言 decode 1000万次耗时
Python 39475 ms
Golang 34513 ms

Golang 相较于 Python,在 json decode 上有明显优势,肉眼观察发现 Golang 程序的 CPU 利用率比 Python 的要高。