TDD & Benchmarking in GO

  • Testing the functions written in GO.
  • Testing a function with multiple values.
  • Reading test-scenarios from Excel and then executing.
  • Benchmarking Applications written in GO.
  • At line #11, we have pointer to “testing.T” being present into it.
  • At line #18, we shall assert the generated value with the static value.
  • Let’s write a method “TestMany” to test the function with multiple values.
  • At line #30, we have created a slice of values, with which we shall be testing the function.
go test sqrt_test.go sqrt.go -v
  • So what we do in the benchmark is we iterate b.N times calling our function.
  • Here, we make sure there was no error and if there is, we’ll fatal the test, meaning stop it right here.
go test sqrt_test.go sqrt.go -v -bench . -run TTT
  • dot means all the benchmarks.
  • If you’re interested only in the benchmarks and not in the tests, you can specify -run with a name that does not match any other test. This way you’ll get only the benchmarks running and not the tests themself.
  • Before optimizing a program, you need to profile it to see where it spends its time.
  • You can use your benchmark for profiling.
  • We’ll do the benchmark and we say — Cpuprofile=prof.out.
  • And now that we have prof.out, we can use the pprof tool. So go tool pprof and then prof.out.
  • To see our function, we do list and Sqrt and we see that the run time of our function.
  • Here we can see every line and how much time it took flat and commulative.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
aditya goel

aditya goel

Software Engineer for Big Data distributed systems