How to use Go language for code stress testing and load testing practice

王林
Release: 2023-08-02 12:09:46
Original
1331 people have browsed it

How to use Go language for code stress testing and load testing practice

Introduction:
In the software development process, performance testing of the code is a very important link. It can help us understand how the code performs under different load conditions and identify potential performance issues. As a high-performance programming language, Go language provides a wealth of tools and libraries that can help us perform code stress testing and load testing. This article will introduce the practice of using Go language for code stress testing and load testing, and provide corresponding code examples.

1. Code stress testing
Code stress testing refers to performance testing of the code by simulating a large number of concurrent requests to evaluate the performance of the code in high concurrency scenarios. Go language provides a built-in net/http/httptest package, making it very simple to write code stress testing scripts. Below we take a simple HTTP service as an example to introduce how to use Go language for code stress testing.

  1. Create an HTTP service
    First, we need to create a simple HTTP service for performance testing. The following is a sample code for a simple HTTP service:
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, World!")
    })

    http.ListenAndServe(":8080", nil)
}
Copy after login
  1. Write a stress test script
    Then, we write a Go script to simulate a large number of concurrent requests for the above HTTP service Conduct performance testing. The following is a simple stress test script example:
package main

import (
    "fmt"
    "net/http"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    start := time.Now()

    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()

            res, err := http.Get("http://localhost:8080")
            if err != nil {
                fmt.Println("Error:", err)
                return
            }
            defer res.Body.Close()
        }()
    }

    wg.Wait()

    elapsed := time.Since(start)
    fmt.Println("Elapsed time:", elapsed)
}
Copy after login

In the above script, we use sync.WaitGroup to wait for all concurrent requests to complete. The stress test script will send 1,000 concurrent requests to http://localhost:8080 and calculate the total time consumption. It is worth noting that this is just a simple example. The actual stress testing script may be more complex and needs to be adjusted according to specific needs.

  1. Run code stress test
    Finally, we can use the go run command to run the above stress test script:
$ go run main.go
Copy after login
Copy after login

After running, You will see the total elapsed time output.

2. Load testing
Load testing refers to simulating actual user behavior and performance testing the entire system to evaluate the performance of the system under high load. Go language provides some great libraries for writing load testing scripts. The following is an example load test script based on the go-vegeta/vegeta library.

  1. Install the vegeta library
    First, we need to install the vegeta library. It can be installed through the following command:
$ go get github.com/tsenart/vegeta
Copy after login
  1. Writing a load test script
    Then, we write a Go script and use the vegeta library to perform load testing. The following is an example of a simple load test script:
package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"

    vegeta "github.com/tsenart/vegeta/lib"
)

func main() {
    rate := vegeta.Rate{Freq: 100, Per: time.Second}
    duration := 10 * time.Second
    targeter := vegeta.NewStaticTargeter(vegeta.Target{
        Method: "GET",
        URL:    "http://localhost:8080",
    })

    attacker := vegeta.NewAttacker()
    var metrics vegeta.Metrics
    sigs := make(chan os.Signal, 1)

    go func() {
        for range sigs {
            attacker.Stop()
        }
    }()
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

    for res := range attacker.Attack(targeter, rate, duration, "Big Bang!") {
        metrics.Add(res)
    }

    metrics.Close()

    fmt.Printf("99th percentile: %s
", metrics.Latencies.P99)
    fmt.Printf("Mean: %s
", metrics.Latencies.Mean)
    fmt.Printf("Requests/sec: %.2f
", metrics.Rate)
    fmt.Printf("Errors: %d
", metrics.Errors)
}
Copy after login

In the above script, we define a load test that sends 100 requests per second for 10 seconds. The load test will send a GET request to http://localhost:8080 and collect various statistics such as 99th percentile, average latency, requests/second, etc.

  1. Run the load test
    Finally, we can use the go run command to run the above load test script:
$ go run main.go
Copy after login
Copy after login

After running, you You will see various statistics output.

Conclusion:
This article introduces the practice of using Go language to conduct code stress testing and load testing, and provides corresponding code examples. Code stress testing and load testing are very important aspects of software development, which can help us evaluate the performance of the code under high concurrency and high load conditions. I hope this article can help you better understand and apply the Go language for performance testing.

The above is the detailed content of How to use Go language for code stress testing and load testing practice. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!