Created
June 25, 2020 01:54
-
-
Save pjebs/f95a53e8e8e37ce8cff879e5451a4d76 to your computer and use it in GitHub Desktop.
go benchmarking: setup and cleanup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var db *sql.DB | |
// Add DB credentials here | |
var ( | |
user string = "" | |
pword string = "" | |
host string = "" | |
port string = "" | |
dbname string = "" | |
) | |
func init() { | |
db, _ = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, pword, host, port, dbname)) | |
db.SetMaxOpenConns(1) | |
err := db.Ping() | |
if err != nil { | |
panic(err) | |
} | |
} | |
func setup() { | |
// Create table | |
createQ := ` | |
CREATE TABLE tests ( | |
id int(11) unsigned NOT NULL AUTO_INCREMENT, | |
name varchar(50) NOT NULL DEFAULT '', | |
email varchar(150) NOT NULL DEFAULT '', | |
PRIMARY KEY (id) | |
)` | |
_, err := db.Exec(createQ) | |
if err != nil { | |
panic(err) | |
} | |
// Add 10,000 fake entries | |
entries := []interface{}{} | |
for i := 0; i < 10000; i++ { | |
entry := []interface{}{ | |
i + 1, | |
gofakeit.Name(), // Fake name | |
gofakeit.Email(), // Fake email | |
} | |
entries = append(entries, entry) | |
} | |
stmt := dbq.INSERTStmt("tests", []string{"id", "name", "email"}, len(entries)) | |
_, err = dbq.E(ctx, db, stmt, nil, entries) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func cleanup() { | |
// Delete table | |
_, err := db.Exec(`DROP TABLE tests`) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func Benchmark(b *testing.B) { | |
setup() | |
defer cleanup() | |
// Benchmark goes in here | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment