0
# Speed Testing
1
2
Primary speed testing functionality through the Speedtest class. Provides comprehensive bandwidth measurement capabilities with server selection, configuration management, and concurrent testing support.
3
4
```python
5
import speedtest
6
```
7
8
## Capabilities
9
10
### Speedtest Class
11
12
Main class for performing internet speed tests with full control over configuration, server selection, and test execution.
13
14
```python { .api }
15
class Speedtest:
16
def __init__(self, config=None, source_address=None, timeout=10, secure=False, shutdown_event=None):
17
"""
18
Initialize Speedtest instance.
19
20
Parameters:
21
- config (dict, optional): Custom configuration dictionary
22
- source_address (str, optional): Source address to bind to
23
- timeout (int): Request timeout in seconds (default: 10)
24
- secure (bool): Use HTTPS connections (default: False)
25
- shutdown_event (threading.Event, optional): Event for graceful shutdown
26
"""
27
```
28
29
**Properties:**
30
- `best` (dict): Best server information (lazy-loaded)
31
- `config` (dict): Configuration dictionary with client info and settings
32
- `servers` (dict): Available servers grouped by distance
33
- `closest` (list): List of closest servers
34
- `results` (SpeedtestResults): Test results object
35
- `lat_lon` (tuple): Client coordinates (latitude, longitude)
36
37
### Configuration Management
38
39
Download and manage speedtest.net configuration including client information and server endpoints.
40
41
```python { .api }
42
def get_config(self):
43
"""
44
Download speedtest configuration from speedtest.net.
45
46
Returns:
47
dict: Configuration containing client info, server URLs, and timing settings
48
49
Raises:
50
ConfigRetrievalError: Failed to download configuration
51
"""
52
```
53
54
Usage example:
55
```python
56
s = speedtest.Speedtest()
57
config = s.get_config()
58
print(f"Client IP: {config['client']['ip']}")
59
print(f"ISP: {config['client']['isp']}")
60
```
61
62
### Server Management
63
64
Retrieve and manage available speed test servers with filtering and selection capabilities.
65
66
```python { .api }
67
def get_servers(self, servers=None, exclude=None):
68
"""
69
Retrieve list of speedtest.net servers.
70
71
Parameters:
72
- servers (list, optional): List of server IDs to retrieve
73
- exclude (list, optional): List of server IDs to exclude
74
75
Returns:
76
dict: Servers grouped by distance from client
77
78
Raises:
79
ServersRetrievalError: Failed to retrieve server list
80
NoMatchedServers: No servers match provided criteria
81
"""
82
83
def get_closest_servers(self, limit=5):
84
"""
85
Get closest servers by geographic distance.
86
87
Parameters:
88
- limit (int): Maximum number of servers to return (default: 5)
89
90
Returns:
91
list: List of closest server dictionaries sorted by distance
92
"""
93
94
def get_best_server(self, servers=None):
95
"""
96
Determine best server by latency testing.
97
98
Parameters:
99
- servers (list, optional): List of servers to test (default: closest servers)
100
101
Returns:
102
dict: Best server information
103
104
Raises:
105
SpeedtestBestServerFailure: Failed to determine best server
106
"""
107
```
108
109
Usage example:
110
```python
111
s = speedtest.Speedtest()
112
s.get_servers()
113
114
# Get 10 closest servers
115
closest = s.get_closest_servers(limit=10)
116
print(f"Found {len(closest)} closest servers")
117
118
# Auto-select best server
119
best = s.get_best_server()
120
print(f"Best server: {best['sponsor']} in {best['name']}")
121
```
122
123
### Mini Server Support
124
125
Support for testing against custom speedtest Mini servers.
126
127
```python { .api }
128
def set_mini_server(self, server):
129
"""
130
Set Mini server URL for testing.
131
132
Parameters:
133
- server (str): Mini server URL
134
135
Raises:
136
InvalidSpeedtestMiniServer: Invalid Mini server URL
137
SpeedtestMiniConnectFailure: Failed to connect to Mini server
138
"""
139
```
140
141
### Speed Testing
142
143
Execute download and upload speed tests with progress callbacks and threading control.
144
145
```python { .api }
146
def download(self, callback=None, threads=None):
147
"""
148
Perform download speed test.
149
150
Parameters:
151
- callback (callable, optional): Progress callback function(bytes_received, total_bytes)
152
- threads (int, optional): Number of threads to use (default: determined by server)
153
154
Returns:
155
float: Download speed in bits per second
156
157
Raises:
158
SpeedtestMissingBestServer: Best server not set (call get_best_server first)
159
"""
160
161
def upload(self, callback=None, pre_allocate=True, threads=None):
162
"""
163
Perform upload speed test.
164
165
Parameters:
166
- callback (callable, optional): Progress callback function(bytes_sent, total_bytes)
167
- pre_allocate (bool): Pre-allocate upload data in memory (default: True)
168
- threads (int, optional): Number of threads to use (default: determined by server)
169
170
Returns:
171
float: Upload speed in bits per second
172
173
Raises:
174
SpeedtestMissingBestServer: Best server not set (call get_best_server first)
175
SpeedtestUploadTimeout: Upload test timed out
176
"""
177
```
178
179
Usage example:
180
```python
181
def progress_callback(bytes_done, total_bytes):
182
percent = (bytes_done / total_bytes) * 100
183
print(f"Progress: {percent:.1f}%")
184
185
s = speedtest.Speedtest()
186
s.get_best_server()
187
188
# Run tests with progress callback
189
download_speed = s.download(callback=progress_callback)
190
upload_speed = s.upload(callback=progress_callback)
191
192
print(f"Download: {download_speed / 1000000:.2f} Mbps")
193
print(f"Upload: {upload_speed / 1000000:.2f} Mbps")
194
```
195
196
## Utility Functions
197
198
```python { .api }
199
def build_user_agent():
200
"""Build HTTP User-Agent string for requests."""
201
202
def distance(origin, destination):
203
"""
204
Calculate distance between coordinate points.
205
206
Parameters:
207
- origin (dict): Origin coordinates with 'lat' and 'lon' keys
208
- destination (dict): Destination coordinates with 'lat' and 'lon' keys
209
210
Returns:
211
float: Distance in kilometers
212
"""
213
```