An extract of the information flow dated March 18, 2021

The original release address: Digest | Go RESTful API benchmark

Learn Golang every day

Benchmark Golang performance | Go RESTful API

Newline: Golang Performance: Benchmarking a Go RESTful API

Go’s performance is good, but the code implementation also has a big impact.

Benchmarks are a testing technique that helps you answer questions such as:

  • “How fast is my code running?
  • “And if I make these changes to my code, will I get a significant performance improvement?”

Benchmarks provide us with actual numbers that quantify the performance of our code.

  • Execution time – How long does it take to run?
  • Total memory allocation – How much memory must be allocated to run?
  • Memory allocation rate – How many times must memory be allocated to meet total memory requirements?
A simple benchmark example
// Returns the sum of two ints
func Sum(a int, b int) {
  // Add the two input numbers
  // return their sum
  return a + b
}
Copy the code
// Import testing library
import (
  "testing"
)

// Benchmark for `Sum` function
func BenchmarkSumFunc(b *testing.B) {
  // Run the function `b.N` times
  for i := 0; i < b.N; i++ {
    Sum(100, i)
  }
}
Copy the code

Test: go test-bench =

Results:

This benchmark runs the Sum function in b.N iterations. In this case, the benchmark ran a billion iterations. On average, 0.6199 ns was run per iteration.

RESTful API benchmark example

newline-sandbox/go-chi-restful-api

  • GET /posts – Retrieves a list of posts.
  • POST /posts – Create a POST.
  • GET /posts/{id} – Retrieve posts by id.
  • PUT /posts/{id} – Update posts by id.
  • DELETE /posts/{id} – DELETE a post by id.
Install dependencies
make install_deps

# Execute the unit test in routes/posts_test.go.
make test
Copy the code

Outes /posts_test.go Benchmarks

// routes/posts_test.go
// ...

func BenchmarkGetPostsHandler( b *testing.B) {
  // Group benchmarks
  b.Run(
   "Endpoint: GET /posts".func(b *testing.B) {
    GetPosts = (
     &JsonPlaceholderMock{}).GetPosts

    // Define the GET request
    // to benchmark
    r, _ := http.NewRequest(
     "GET"."/posts".nil)

    // Create a response recorder
    w := httptest.NewRecorder()

    // Create an HTTP route handler
    handler := http.HandlerFunc(
     PostsResource{}.List)

    // Turn on memory stats
    b.ReportAllocs()
    b.ResetTimer()

    // Execute the handler
    // with a request, `b.N` times
    for i := 0; i < b.N; i++ {
      handler.ServeHTTP(w, r)
    }
  })
}
Copy the code

In the code above, we use B.run to group benchmarks by the functionality of the tests. To avoid sending network requests during benchmarking, we simulated the scope variable of the GetPosts package. We create a new GET request and send it to /posts via the HTTP package’s NewRequest method.

We also created a response logger via httpTest. NewRecorder to record the ResponseWriter mutation. The PostsResource{}.List method is an ordinary function. Therefore, we pass it to the HandlerFunc method of the HTTP package, from which we create an HTTP route handler.

We turn on malloc statistics with b.reportallocs to display two additional columns in the output. These two columns tell us how many bytes of memory are allocated per iteration on average, and how many allocations are performed per iteration.

The handler.ServeHTTP method uses the response logger W and the created request R to perform the HTTP route handler representation of PostsResource{}.list.

We loop through handler.ServeHTTP until the benchmark determines how fast it should run. The value of b.N varies until the benchmark stabilizes and knows how long it must run to properly time the function.

Run the benchmark
go test -bench=. ./routes -run=^$
Copy the code
  • -bench=.– Tells GO test to run benchmarks and tests in the _test.go file of the project. . Is a regular expression that tells go test to match everything.
  • ./routes– Tells go test where to run benchmarks and tests in the _test.go file.
  • -run=^$– Tells go test that the run name satisfies the regular expression^ $The test. Since none of the tests are named with$Start, so Go Test doesn’t run any tests, just the benchmark.

The benchmark ran a total of 97,220 iterations, with an average of 11,439ns per iteration. This represents the average time it took each handler.ServeHTTP function and PostsResource{}.List call to complete. Each iteration involved allocating an average of 33,299 bytes of memory. On average, memory is allocated 8 times per iteration.

The purpose of benchmarking is that we can determine the best performance by changing the procedural implementation of the code. This is often done in open source projects, where major upgrades include new implementations that provide a more efficient set of routines for basic tasks.

Learn Linux every day

5 super handy Linux commands

5 Super Handy Linux Commands that Everyone Should be Aware of

# Killall exactly matches the argument name by default and kills the matching process. Here is how to use it
# -I option to ignore the case.
killall -I notes

# edit long command
Ctrl + x + e

# tee vs. >> : In addition to writing to files, Tee copies data to STDOUT.
echo 123 | tee test.txt

# edit last command
fc
Copy the code

Learn something about marketing every day

Google Analytics collects activity data using custom urls

Collect campaign data with custom URLs

By adding campaign parameters to the target urls you use in your advertising campaigns, you can gather information about the overall effectiveness of those campaigns, and you can also see where the campaigns are more effective.

  • Utm_source. Identify advertisers, websites, publications, etc., that are sending traffic meta, e.g. : Google, Newsletter 4, billboards.
  • Utm_medium: Advertising or marketing media, e.g. CPC, banners, email newsletters.
  • Utm_campaign: A single campaign name, slogan, promotion code, and so on for a product.
  • Utm_term. Identify paid search terms. If you are manually marking paid keyword activities, you should also use UTM_term to specify keywords.
  • Utm_content. Used to distinguish similar content, or links within the same AD. For example, if you have two call action links in the same E-mail, you can use UTM_content and set a different value for each link so that you can determine which version is more effective.
The URL generated
  • Site link: Use the Campaign URL Builder at Google Analytics Demos & Tools

  • Android App: Use Google Play URL Builder. You must also set Google Play Campaign Attribution in the SDK. If you didn’t complete this feature during the initial setup, please use our Developer’s Guide to learn how to implement Google Play Attribution in your Android SDK.

  • IOS – App ads. Use the iOS Campaign Tracking URL Builder.

View custom data

Log on to Google Analytics. Go to the view. Open the Reports. Select Acquisition > Campaigns.

 

Others worth reading

  • Focalboard: Opens from a managed project management system (notion like). Focalboard: Open source, self-hosted project management

  • I did over 30 projects using React/Nextjs as the front end and various stacks as the back end: I made 30+ project using React / Nextjs as frontend and various stacks as a Backend(MongoDB,Nodejs,Express,Firebase,Airtable,Prisma…) . Please feel free to check em out.