Sobes.tech
Junior — Middle

How to measure the access speed to array elements in a program?

sobes.tech AI

Answer from AI

To measure the access speed to array elements in Go, you can use the time package to measure the execution time of a loop that sequentially accesses array elements. For example:

package main

import (
    "fmt"
    "time"
)

func main() {
    arr := make([]int, 1000000)
    // Fill the array
    for i := range arr {
        arr[i] = i
    }

    start := time.Now()
    sum := 0
    for i := 0; i < len(arr); i++ {
        sum += arr[i]
    }
    elapsed := time.Since(start)

    fmt.Printf("Sum: %d, Access time: %s\n", sum, elapsed)
}

This approach provides an approximate time for sequential access to array elements. For more precise measurements, you can use benchmarks with the testing package.

How to measure the access speed to array elements in… - sobes.tech