设计一个 Postman-like 工具,并实现API 接口测速,通常可以采用以下方式:
测速方法
- 发送请求前 记录 时间戳
t1
。 - 请求完成后 记录 时间戳
t2
。 - 计算接口响应时间:
[ \text{responseTime} = t2 - t1 ] - 多次请求,取平均值(如:10 次请求,计算平均响应时间)。
- 可视化响应时间曲线(折线图、柱状图)。
实现方案
方案 1:使用 JavaScript 进行测速
适用于浏览器环境,如 Postman 扩展插件或 Web 版工具。
async function testApiSpeed(url, method = 'GET', body = null, headers = {}) {
const numRequests = 5; // 测试次数
let totalTime = 0;
let results = [];
for (let i = 0; i < numRequests; i++) {
const t1 = performance.now(); // 记录开始时间
await fetch(url, {
method: method,
headers: headers,
body: body ? JSON.stringify(body) : null,
});
const t2 = performance.now(); // 记录结束时间
const timeTaken = t2 - t1; // 计算响应时间
totalTime += timeTaken;
results.push(timeTaken);
console.log(`请求 ${i + 1}: ${timeTaken.toFixed(2)} ms`);
}
const avgTime = totalTime / numRequests;
console.log(`平均响应时间: ${avgTime.toFixed(2)} ms`);
return { avgTime, results };
}
// 使用示例
testApiSpeed('https://jsonplaceholder.typicode.com/todos/1').then((data) =>
console.log('测速完成', data),
);
特点:
✅ 适用于 Web 端,可在浏览器执行
✅ 可集成到 Web 版 Postman
❌ fetch
受跨域限制,部分 API 可能无法测速
方案 2:使用 Node.js 进行 API 测速
适用于后端或命令行工具,使用 axios
。
安装依赖
npm install axios
测速代码
const axios = require('axios');
async function testApiSpeed(url, method = 'GET', data = null, headers = {}) {
const numRequests = 5;
let totalTime = 0;
let results = [];
for (let i = 0; i < numRequests; i++) {
const t1 = process.hrtime(); // 高精度时间
await axios({ method, url, headers, data });
const t2 = process.hrtime(t1); // 计算差值
const timeTaken = t2[0] * 1000 + t2[1] / 1e6; // 转换为 ms
totalTime += timeTaken;
results.push(timeTaken);
console.log(`请求 ${i + 1}: ${timeTaken.toFixed(2)} ms`);
}
const avgTime = totalTime / numRequests;
console.log(`平均响应时间: ${avgTime.toFixed(2)} ms`);
return { avgTime, results };
}
// 使用示例
testApiSpeed('https://jsonplaceholder.typicode.com/todos/1').then((data) =>
console.log('测速完成', data),
);
特点:
✅ 后端无跨域问题,可测试任意 API
✅ 高精度时间(process.hrtime()
)
✅ 适用于 CLI 或 Web 端 (支持 Express API 测速)
方案 3:使用 Python 进行 API 测速
适用于 CLI 或服务器端,使用 requests
库。
安装 requests
pip install requests
测速代码
import time
import requests
def test_api_speed(url, method="GET", data=None, headers=None, num_requests=5):
total_time = 0
results = []
for i in range(num_requests):
t1 = time.time()
response = requests.request(method, url, json=data, headers=headers)
t2 = time.time()
time_taken = (t2 - t1) * 1000 # 转换为毫秒
total_time += time_taken
results.append(time_taken)
print(f"请求 {i+1}: {time_taken:.2f} ms")
avg_time = total_time / num_requests
print(f"平均响应时间: {avg_time:.2f} ms")
return {"avg_time": avg_time, "results": results}
### 使用示例
test_api_speed("https://jsonplaceholder.typicode.com/todos/1")
特点:
✅ 适用于服务器端,无跨域问题
✅ requests
库简单易用,支持 JSON/表单请求
✅ 适用于 自动化测试、批量测速
方案 4:可视化 API 响应时间
使用 matplotlib
绘制响应时间曲线
import time
import requests
import matplotlib.pyplot as plt
def test_api_speed(url, num_requests=5):
times = []
for i in range(num_requests):
t1 = time.time()
requests.get(url)
t2 = time.time()
times.append((t2 - t1) * 1000) # 转换为毫秒
return times
### 测速
api_url = "https://jsonplaceholder.typicode.com/todos/1"
results = test_api_speed(api_url, num_requests=10)
### 绘图
plt.plot(range(1, len(results) + 1), results, marker='o', linestyle='-')
plt.xlabel("请求次数")
plt.ylabel("响应时间 (ms)")
plt.title("API 响应时间测试")
plt.show()
方案 5:使用 Apache Benchmark(AB) 测 API
适用于高并发压力测试
ab -n 100 -c 10 https://jsonplaceholder.typicode.com/todos/1
-
-n 100
→ 总请求数 100 -
-c 10
→ 并发数 10
总结
方案 | 适用环境 | 适用人群 | 主要特点 |
---|---|---|---|
JavaScript (fetch ) | 浏览器 | Web 开发者 | 适用于前端测速,受跨域限制 |
Node.js (axios ) | 后端/CLI | 后端开发 | 适用于服务器端,高精度时间 |
Python (requests ) | 服务器/CLI | 自动化测试 | 适用于批量 API 测速 |
Matplotlib 可视化 | 服务器 | 数据分析 | 绘制 API 响应时间趋势图 |
Apache Benchmark (ab ) | 服务器 | 压测人员 | 适用于高并发压力测试 |
最佳选择
-
前端 Web 版 Postman → 方案 1(fetch)
-
后端/CLI API 测速 → 方案 2(Node.js axios)
-
自动化测试 → 方案 3(Python requests)
-
可视化 API 响应曲线 → 方案 4(Matplotlib)
-
API 压测/并发测试 → 方案 5(Apache Benchmark)
你想要哪种方式?🚀
最后更新于: