Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - showwin/speedtest-go: CLI and Go API to Test Internet Speed using speedtest.net · GitHub
Skip to content

Repository files navigation

speedtest-go

Full-featured Command Line Interface and pure Go API to Test Internet Speed using speedtest.net.

You can speedtest 2x faster than speedtest.net with almost the same result. See the experimental results. Inspired by sivel/speedtest-cli

CLI

Installation

macOS (homebrew)

$ brew tap showwin/speedtest
$ brew install speedtest
### How to Update ###
$ brew update
$ brew upgrade speedtest

Nix (package manager)

# Enter the latest speedtest-go environment
$ nix-shell -p speedtest-go

Other Platforms (Linux, Windows, etc.)

Please download the compatible package from Releases. If there are no compatible packages you want, please let me know on Issue Tracker.

Docker Build

To build a multi-architecture Docker image:

# Check if you already have a builder instance
docker buildx ls
# Only create a new builder if you don't have one# If the above command shows no builders or none are in use, run:
docker buildx create --name mybuilder --use
# Build and push for multiple platforms
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t yourusername/speedtest-go:latest --push .

Running the Container

Docker

Run the container with default settings (interactive shell):

docker run -it yourusername/speedtest-go:latest

Run a speedtest with specific arguments:

# Run a basic speedtest
docker run yourusername/speedtest-go:latest speedtest-go
# Run with specific server
docker run yourusername/speedtest-go:latest speedtest-go --server 6691
# Run with multiple servers and JSON output
docker run yourusername/speedtest-go:latest speedtest-go --server 6691 --server 6087 --json
# Run with custom location
docker run yourusername/speedtest-go:latest speedtest-go --location=60,-110
Kubernetes

Here's an example Kubernetes pod specification that runs a speedtest:

apiVersion: v1kind: Podmetadata:
name: speedtestspec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latest# Base command to run bashcommand: ["speedtest-go"]# Or run with specific arguments# args: ["--server", "6691", "--json"]restartPolicy: Never

For a more complete deployment, you might want to use a CronJob to run periodic speedtests:

apiVersion: batch/v1kind: CronJobmetadata:
name: speedtestspec:
schedule: "0 */6 * * *"# Run every 6 hoursjobTemplate:
spec:
template:
spec:
containers:
- name: speedtestimage: yourusername/speedtest-go:latestcommand: ["speedtest-go"]args: ["--json"]restartPolicy: OnFailure

Usage

$ speedtest --help
usage: speedtest-go [<flags>]
Flags:
--help Show context-sensitive help (also try --help-long and --help-man).
-l, --list Show available speedtest.net servers.
-s, --server=SERVER ... Select server id to speedtest.
--custom-url=CUSTOM-URL Specify the url of the server instead of fetching from speedtest.net.
--saving-mode Test with few resources, though low accuracy (especially > 30Mbps).
--json Output results in json format.
--jsonl Output results in jsonl format (one json object per line).
--unix Output results in unix like format.
--location=LOCATION Change the location with a precise coordinate (format: lat,lon).
--city=CITY Change the location with a predefined city label.
--city-list List all predefined city labels.
--proxy=PROXY Set a proxy(http[s] or socks) for the speedtest.
eg: --proxy=socks://10.20.0.101:7890
eg: --proxy=http://10.20.0.101:7890
--source=SOURCE Bind a source interface for the speedtest.
--dns-bind-source DNS request binding source (experimental).
eg: --source=10.20.0.101
eg: --source=eth0 (Linux only)
-m --multi Enable multi-server mode.
-t --thread=THREAD Set the maximum concurrent connections (upload adapts automatically; default cap 8).
--search=SEARCH Fuzzy search servers by a keyword.
--ua Set the user-agent header for the speedtest.
--no-download Disable download test.
--no-upload Disable upload test.
--ping-mode Select a method for Ping (support icmp/tcp/http).
-p, --protocol Select the download/upload protocol [http (default) or tcp (experimental)].
-u --unit Set human-readable and auto-scaled rate units for output (options: decimal-bits/decimal-bytes/binary-bits/binary-bytes).
--filter-cc=FILTER-CC Filter servers by Country Code(s). (options: CC/auto).
eg: --filter-cc=JP
eg: --filter-cc=auto
--mask-isp Mask sensitive info (IP address and coordinates) in ISP output.
-d --debug Enable debug mode.
--version Show application version.

Test Internet Speed

Simply use speedtest command. The closest server is selected by default. Use the -m flag to enable multi-measurement mode (recommended)

## unix like format output# speedtest --unix
$ speedtest
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 20 Public Servers
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 4.452963ms Jitter: 41.271µs Min: 4.395179ms Max: 4.517576ms
✓ Packet Loss Analyzer: Running in background (<= 30 Secs)
✓ Download: 115.52 Mbps (Used: 135.75MB) (Latency: 4ms Jitter: 0ms Min: 4ms Max: 4ms)
✓ Upload: 4.02 Mbps (Used: 6.85MB Confirmed: 96.0%) (Latency: 4ms Jitter: 1ms Min: 3ms Max: 8ms)
✓ Packet Loss: 8.82% (Sent: 217/Dup: 0/Max: 237)

For upload results, Confirmed indicates the proportion of uploaded bytes confirmed by a successful upload response.

Test with Other Servers

If you want to select other servers to test, you can see the available server list.

$ speedtest --list
Testing From IP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
[6691] 9.03km 32.3365ms Shizuoka (Japan) by sudosan
[6087] 120.55km 51.7453ms Fussa-shi (Japan) by Allied Telesis Capital Corporation
[6508] 125.44km 54.6683ms Yokohama (Japan) by at2wn
[6424] 148.23km 61.4724ms Tokyo (Japan) by Cordeos Corp.
...

and select them by id.

$ speedtest --server 6691 --server 6087
speedtest-go v1.8.3 @showwin
✓ ISP: 124.27.199.165 (Fujitsu) [34.9769, 138.3831]
✓ Found 2 Specified Public Server(s)
✓ Test Server: [6691] 9.03km Shizuoka (Japan) by sudosan
✓ Latency: 21.424ms Jitter: 1.644ms Min: 19.142ms Max: 23.926ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 65.82Mbps (Used: 75.48MB) (Latency: 22ms Jitter: 2ms Min: 17ms Max: 24ms)
✓ Upload: 27.00Mbps (Used: 36.33MB) (Latency: 23ms Jitter: 2ms Min: 18ms Max: 25ms)
✓ Packet Loss: 0.00% (Sent: 321/Dup: 0/Max: 320)
✓ Test Server: [6087] 120.55km Fussa-shi (Japan) by Allied Telesis Capital Corporation
✓ Latency: 38.694699ms Jitter: 2.724ms Min: 36.443ms Max: 39.953ms
✓ Packet Loss Analyzer: Running in background (<= 30 Sec)
✓ Download: 72.24Mbps (Used: 83.72MB) (Latency: 37ms Jitter: 3ms Min: 36ms Max: 40ms)
✓ Upload: 29.56Mbps (Used: 47.64MB) (Latency: 38ms Jitter: 3ms Min: 37ms Max: 41ms)
✓ Packet Loss: 0.00% (Sent: 343/Dup: 0/Max: 342)

Test with a virtual location

With --city or --location option, the closest servers of the location will be picked. You can measure the speed between your location and the target location.

$ speedtest --city-list
Available city labels (case insensitive):
CC CityLabel Location
(za) capetown [-33.9391993, 18.4316716]
(pl) warsaw [52.2396659, 21.0129345]
(sg) yishun [1.4230218, 103.8404728]
...
$ speedtest --city=capetown
$ speedtest --location=60,-110

Memory Saving Mode

With --saving-mode option, it can be executed even in an insufficient memory environment like IoT devices. The memory usage can be reduced to 1/10, about 10MB of memory is used.

However, please be careful that the accuracy is particularly low, especially in an environment of 30 Mbps or higher. To get more accurate results, run multiple times and average.

For more details, please see saving mode experimental result.

⚠️This feature has been deprecated > v1.4.0, because speedtest-go can always run with less than 10MBytes of memory now. Even so, --saving-mode is still a good way to reduce computation.

Go API

go get github.com/showwin/speedtest-go

API Usage

The code below finds the closest available speedtest server and tests the latency, download, and upload speeds.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest"
)
funcmain() {
varspeedtestClient=speedtest.New()
// Use a proxy for the speedtest. eg: socks://127.0.0.1:7890// speedtest.WithUserConfig(&speedtest.UserConfig{Proxy: "socks://127.0.0.1:7890"})(speedtestClient)// Select a network card as the data interface.// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "192.168.1.101"})(speedtestClient)// On Linux, a network interface name also works (binds via SO_BINDTODEVICE):// speedtest.WithUserConfig(&speedtest.UserConfig{Source: "eth0"})(speedtestClient)// Get user's network information// user, _ := speedtestClient.FetchUserInfo()// Get a list of servers near a specified location// user.SetLocationByCity("Tokyo")// user.SetLocation("Osaka", 34.6952, 135.5006)// Search server using serverID.// eg: fetch server with ID 28910.// speedtest.ErrServerNotFound will be returned if the server cannot be found.// server, err := speedtest.FetchServerByID("28910")serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
for_, s:=rangetargets {
// Please make sure your host can access this test server,// otherwise you will get an error.// It is recommended to replace a server at this times.PingTest(nil)
s.DownloadTest()
s.UploadTest()
// Note: The unit of s.DLSpeed, s.ULSpeed is bytes per second, this is a float64.fmt.Printf("Latency: %s, Download: %s, Upload: %s\n", s.Latency, s.DLSpeed, s.ULSpeed)
s.Context.Reset() // reset counter
}
}

The code will find the closest available speedtest server and analyze packet loss.

package main
import (
"fmt""github.com/showwin/speedtest-go/speedtest""github.com/showwin/speedtest-go/speedtest/transport""log"
)
funccheckError(errerror) {
iferr!=nil {
log.Fatal(err)
}
}
// Note: The current packet loss analyzer does not support udp over http.// This means we cannot get packet loss through a proxy.funcmain() {
// Retrieve available serversvarspeedtestClient=speedtest.New()
serverList, _:=speedtestClient.FetchServers()
targets, _:=serverList.FindServer([]int{})
// Create a packet loss analyzer, use default optionsanalyzer:=speedtest.NewPacketLossAnalyzer(nil)
// Perform packet loss analysis on all available serversfor_, server:=rangetargets {
err:=analyzer.Run(server.Host, func(packetLoss*transport.PLoss) {
fmt.Println(packetLoss, server.Host, server.Name)
// fmt.Println(packetLoss.Loss())
})
checkError(err)
}
// or test all at the same time.packetLoss, err:=analyzer.RunMulti(targets.Hosts())
checkError(err)
fmt.Println(packetLoss)
}

Summary of Experimental Results

Speedtest-go is a great tool because of the following five reasons:

  • Cross-platform available.
  • Low memory environment.
  • We are the first FULL-FEATURED open source speed testing project based on speedtest.net, including down/up rates, jitter and packet loss, etc.
  • Testing time is the SHORTEST compare to speedtest.net and sivel/speedtest-cli, especially about 2x faster than speedtest.net.
  • Result is MORE CLOSE to speedtest.net than speedtest-cli.

The following data is summarized. If you got interested, please see more details.

Download (Mbps)

distance = distance to testing server

  • 0 - 1000(km) ≒ domestic
  • 1000 - 8000(km) ≒ same region
  • 8000 - 20000(km) ≒ really far!
  • 20000km is half of the circumference of our planet.
distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100092.1291.2170.27
1000 - 800066.4565.5156.56
8000 - 2000011.849.4311.87

Upload (Mbps)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100065.5647.5836.16
1000 - 800058.0254.7426.78
8000 - 200005.208.322.58

Testing Time (sec)

distance (km)speedtest.netspeedtest-gospeedtest-cli
0 - 100045.0322.8424.46
1000 - 800044.8924.4528.52
8000 - 2000049.6434.0841.26

Contributors

See Contributors, PRs are welcome!

Issues

You can find or report issues in the Issue Tracker.

LICENSE

MIT

About

CLI and Go API to Test Internet Speed using speedtest.net

Topics

Resources

Stars

839 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages