Skip to content

Instantly share code, notes, and snippets.

@pjebs
Created June 25, 2020 01:54
Show Gist options
  • Save pjebs/f95a53e8e8e37ce8cff879e5451a4d76 to your computer and use it in GitHub Desktop.
Save pjebs/f95a53e8e8e37ce8cff879e5451a4d76 to your computer and use it in GitHub Desktop.
go benchmarking: setup and cleanup
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