首页 > 其他分享 >Go - Avoiding Test Fixtures in Performance Tests

Go - Avoiding Test Fixtures in Performance Tests

时间:2023-10-18 20:24:39浏览次数:35  
标签:load sausheong Tests Avoiding flip test grid Test benchmarking

Problem: You want to customize the performance tests to avoid benchmarking test fixtures.

Solution: You can start, stop, and reset the benchmark timers using the StartTimer , StopTimer , and ResetTimer , respectively. This will allow you the flexibility to avoid test fixtures.

 

As with functional tests, you will sometimes need to set up test fixtures before running the performance test. Here is an example where you want to take an image file and flip it. In this example, you want to flip a PNG - format image of the Mona Lisa.

The algorithm is easy, and you first load the image file into a 2D grid of pixels (where a pixel is represented by a color.Color struct).

The specific code you want to test is the flip function that takes the grid and flips the pixels in them:

func flip(grid [][]color.Color) {
    for x := 0; x < len(grid); x++ {
        col := grid[x]
        for y := 0; y < len(col)/2; y++ {
            k := len(col) - y - 1
            col[y], col[k] = col[k], col[y]
        }
    }
}

The test fixture you need to set up is to take a PNG file and load it into a grid to get it ready for testing:

func BenchmarkFlip(b *testing.B) {
    grid := load("monalisa.png")
    for i := 0; i < b.N; i++ {
        flip(grid)
    }
}

Let’s run this benchmark function:
% go test - v - bench=Flip - run=XXX

goos: darwin

goarch: arm64

pkg: github.com/sausheong/gocookbook/ch19_benchmarking

BenchmarkFlip

BenchmarkFlip - 10 6492 184067 ns/op

PASS

ok github.com/sausheong/gocookbook/ch19_benchmarking 1.538s

You can see that it takes around 184,067 nanoseconds (or around 184 microseconds) on average to do this. But wait, there is an issue here because the benchmark timer starts at the beginning of the benchmark function, which means this timing includes the setup activity of loading up the file. To overcome this, you need to reset the timer after doing the setup activities by calling b.ResetTimer() after loading the PNG file:

func BenchmarkFlip(b *testing.B) {
    grid := load("monalisa.png")
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        flip(grid)
    }
}

Run it again and see what happens:
% go test - v - bench=Flip - run=XXX

goos: darwin

goarch: arm64

pkg: github.com/sausheong/gocookbook/ch19_benchmarking

BenchmarkFlip

BenchmarkFlip - 10 6618 181478 ns/op

PASS

ok github.com/sausheong/gocookbook/ch19_benchmarking 2.338s

The timing is now about 181 microseconds instead, about 3 microseconds difference.

This is great for setting up before you get into the benchmarking loop. For example, you need to actually do something every iteration and not just once before the start of the loop:

func BenchmarkLoadAndFlip(b *testing.B) {
    for i := 0; i < b.N; i++ {
        grid := load("monalisa.png")
        flip(grid)
    }
}

Take a look at the timing:
% go test - v - bench=LoadAndFlip - run=XXX

goos: darwin

goarch: arm64

pkg: github.com/sausheong/gocookbook/ch19_benchmarking

BenchmarkLoadAndFlip

BenchmarkLoadAndFlip - 10 69 14613379 ns/op

PASS

ok github.com/sausheong/gocookbook/ch19_benchmarking 1.232s

This took about 14.6 milliseconds. To ignore the timing for loading the image file, you need to stop the timer before calling load and start the timer afterward. For this, you can use the StopTimer and StartTimer to control which parts of the iteration you don’t want to benchmark:

func BenchmarkLoadAndFlip(b *testing.B) {
    for i := 0; i < b.N; i++ {
        b.StopTimer()
        grid := load("monalisa.png")
        b.StartTimer()
        flip(grid)
    }
}

Run it again and see the results:

% go test - v - bench=LoadAndFlip - run=XXX

goos: darwin

goarch: arm64

pkg: github.com/sausheong/gocookbook/ch19_benchmarking

BenchmarkLoadAndFlip

BenchmarkLoadAndFlip - 10 1540 672674 ns/op

PASS

ok github.com/sausheong/gocookbook/ch19_benchmarking 23.672s

The timing for the flip function is about 0.67 milliseconds. However, the entire performance test took a lot longer, almost 24 seconds! This is because the flip function is much faster than the load function, and therefore you could do many more iterations (1,540 compared with 69 earlier). However, even though you are not considering the timing for the load function in the performance test, it still executes and takes much longer.

标签:load,sausheong,Tests,Avoiding,flip,test,grid,Test,benchmarking
From: https://www.cnblogs.com/zhangzhihui/p/17773239.html

相关文章

  • Go - Changing the Timing for Running Performance Tests
    Problem: Youwanttorunperformancetestsforaspecificdurationoraspecificnumberofiterations.Solution: Youcanincreasetheminimumdurationthebenchmarksshouldrunorincreasethenumberofiterationsusingthe-benchtimeflag. Torunthis......
  • 最详细的 T Test 方差分析结果解读
    PValue:P值(Pvalue)是在假设检验中一个非常关键的概念。它提供了一个量化的方法来评估观察到的数据与零假设(nullhypothesis)下期望的数据之间的差异。具体来说,P值是在零假设为真的条件下,观察到当前统计量或更极端统计量的概率。以下是关于P值的更详细解释:定义:P值是给定零假设......
  • Go - Testing a Web Application or a Web Service
    Problem: Youwanttodounittestingonawebapplicationorawebservice.Solution: Usethehttptest.NewRecorderfunctiontocreateanhttptest.ResponseRecorderthatcanbeusedtorecordwhat’sbeenwrittentothehttp.ResponseWriter.Thiscanthenb......
  • Go - Generating Random Test Inputs for Tests
    Problem: Youwanttogeneraterandomtestdataforrunningyourtestfunctions. Solution: Usefuzzing,whichisanautomatedtestingtechniquetogeneraterandomtestdataforyourtestfunctions. Fuzzing,orfuzztesting,isanautomatedtestingte......
  • Go - Creating Subtests to Have Finer Control Over Groups of Test Cases
    Problem: Youwanttocreatesubtestswithinatestfunctiontohavefinercontrolovertestcases.Solution: Usethet.Runfunctiontocreatesubtestswithinatestfunction.Subtestsextendtheflexibilityoftestfunctionstoanotherleveldown. When......
  • AtCoder Regular Contest 167
    Preface补一下上周日的ARC,因为当天白天和队友一起VP了一场所以就没有精力再打一场了这场经典C计数不会D这种贪心乱搞反而是一眼秒了,后面的EF过的太少就没看A-ToastsforBreakfastParty用一个类似于蛇形的放法就好了,比如对于\(n=9,m=5\),放法为:567894321#includ......
  • Go - Setting Up and Tearing Down Before and After Tests
    Problem: Youwanttosetupdataandanenvironmentfortestingandtearitdownafterthetestisrun.Solution: YoucancreatehelperfunctionsorusetheTestMainfeaturetocontroltheflowofthetestfunctions. Testingoftenneedsdataandanenv......
  • m基于FPGA的GFDM调制解调系统verilog实现,包含testbench仿真测试文件
    1.算法仿真效果本系统进行了Vivado2019.2平台的开发,测试结果如下:   GFDM调制信号放大:   GFDM解调信号放大:   系统RTL结构图如下:   2.算法涉及理论知识概要        随着通信技术的不断发展,人们对数据传输速率和频谱效率的要求越来越高。......
  • Japan Registry Services (JPRS) Programming Contest 2023 (AtCoder Beginner Contes
    JapanRegistryServices(JPRS)ProgrammingContest2023(AtCoderBeginnerContest324)赛后总结可悲的是:我没来得及写题解。T1Same秒切。直接输入排一遍序再遍历即可。#include<bits/stdc++.h>usingnamespacestd;intn,a[101];intmain(){cin>>n;f......
  • 比赛总结:Japan Registry Services (JPRS) Programming Contest 2023 (AtCoder Beginn
    比赛:JapanRegistryServices(JPRS)ProgrammingContest2023(AtCoderBeginnerContest324)A-same1.常规方法intmain(){ intn; cin>>n; vector<int>s(n);//利用vector容器可以不需要确定内存大小 for(auto&n:s) { cin>>n; } for(inti=0;i......