benchmark_go18_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. // +build go1.8
  9. package mysql
  10. import (
  11. "context"
  12. "database/sql"
  13. "fmt"
  14. "runtime"
  15. "testing"
  16. )
  17. func benchmarkQueryContext(b *testing.B, db *sql.DB, p int) {
  18. ctx, cancel := context.WithCancel(context.Background())
  19. defer cancel()
  20. db.SetMaxIdleConns(p * runtime.GOMAXPROCS(0))
  21. tb := (*TB)(b)
  22. stmt := tb.checkStmt(db.PrepareContext(ctx, "SELECT val FROM foo WHERE id=?"))
  23. defer stmt.Close()
  24. b.SetParallelism(p)
  25. b.ReportAllocs()
  26. b.ResetTimer()
  27. b.RunParallel(func(pb *testing.PB) {
  28. var got string
  29. for pb.Next() {
  30. tb.check(stmt.QueryRow(1).Scan(&got))
  31. if got != "one" {
  32. b.Fatalf("query = %q; want one", got)
  33. }
  34. }
  35. })
  36. }
  37. func BenchmarkQueryContext(b *testing.B) {
  38. db := initDB(b,
  39. "DROP TABLE IF EXISTS foo",
  40. "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))",
  41. `INSERT INTO foo VALUES (1, "one")`,
  42. `INSERT INTO foo VALUES (2, "two")`,
  43. )
  44. defer db.Close()
  45. for _, p := range []int{1, 2, 3, 4} {
  46. b.Run(fmt.Sprintf("%d", p), func(b *testing.B) {
  47. benchmarkQueryContext(b, db, p)
  48. })
  49. }
  50. }
  51. func benchmarkExecContext(b *testing.B, db *sql.DB, p int) {
  52. ctx, cancel := context.WithCancel(context.Background())
  53. defer cancel()
  54. db.SetMaxIdleConns(p * runtime.GOMAXPROCS(0))
  55. tb := (*TB)(b)
  56. stmt := tb.checkStmt(db.PrepareContext(ctx, "DO 1"))
  57. defer stmt.Close()
  58. b.SetParallelism(p)
  59. b.ReportAllocs()
  60. b.ResetTimer()
  61. b.RunParallel(func(pb *testing.PB) {
  62. for pb.Next() {
  63. if _, err := stmt.ExecContext(ctx); err != nil {
  64. b.Fatal(err)
  65. }
  66. }
  67. })
  68. }
  69. func BenchmarkExecContext(b *testing.B) {
  70. db := initDB(b,
  71. "DROP TABLE IF EXISTS foo",
  72. "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))",
  73. `INSERT INTO foo VALUES (1, "one")`,
  74. `INSERT INTO foo VALUES (2, "two")`,
  75. )
  76. defer db.Close()
  77. for _, p := range []int{1, 2, 3, 4} {
  78. b.Run(fmt.Sprintf("%d", p), func(b *testing.B) {
  79. benchmarkQueryContext(b, db, p)
  80. })
  81. }
  82. }