ข้ามไปยังเนื้อหา
TH
รับคีย์ API
เรียกดูเอกสาร

คู่มือ

วัดเวลาแฝง API และอัตราการดาวน์โหลด

ตรวจ สอบ หนึ่ง ครั้ง สรุป บันทึก ตัว อย่าง หรือ ส่ง สื่อ เวลา ไป ยัง ห้อง เก็บ ของ.

ในหน้านี้

เลือกขนาด

เมตริกเริ่ม ○ finish
เวลาการตอบกลับสําหรับค้นหาเริ่ม HTTP ○ อ่าน ร่าง กาย ครบ ชุด. ใช้ขั้นตอน 1–3 ด้านล่างนี้
การส่งสื่อผ่านทางผ่านจำนวนไบต์ของสื่อที่ส่งสำเร็จ ÷ เวลาตั้งแต่เริ่ม CLI จนได้ผลลัพธ์เป็นวินาที รวมการตรวจสอบสิทธิ์ การส่งคำขอ การตรวจสอบสถานะ และการส่งออกผลลัพธ์
Async API เวลาการ ยอม รับ การ บันทึก เสียง (request ob) ID* แยกกันจากความสมบูรณ์ (requested status). ใช้ การ ไหล เวียน ของ แอ ส ยอน และ รักษา ระยะ การ ออก เสียง.

1. เตรียมตัวอย่างการค้นหา

ใช้ Python 3.10+ และกุญแจด้วย google_search อนุญาตให้เข้า FLASHDATA_API_KEY. ไม่มีเพิ่มเติม Python ต้องการแพกเกจครับ ใช้ python3 แทน pythaon ถ้านั่นคือชื่อล่ามของคุณ

สร้างโฟลเดอร์ที่ทํางาน บันทึกสคริปต์ทั้งหมดไว้ด้านล่างโฟลเดอร์นี้ และประมวลผลคําสั่งของมันที่นี่ การค้นหาตัวใหม่แต่ละรายการ จะส่งการสอบถามไปหนึ่งรอบโดยไม่ต้องทําการแก้ไขโดยอัตโนมัติ; การขอข้อมูลแบบธรรมดาใช้ได้

เทอร์มินัล '% 1' สร้างโฟลเดอร์ที่ทํางาน
mkdir flashdata-benchmark
cd flashdata-benchmark
python --version

บันทึกการร้องขอ

บันทึกนี้เป็น request.json ภายใน flashdata-benchmark/.

request.json
{
  "source": "google_search",
  "query": "battery recycling research",
  "params": {
    "num": 5
  }
}

2. เวลาตอบสนองเต็ม

บันทึก measure.py ข้าง request.json. มันคัดลอกคําขอเข้าไปในโฟลเดอร์ตัวอย่างใหม่ แล้วบันทึกเวลาตอบสนองที่สมบูรณ์ HTTP สถานะ, การร้องขอ ID ถึง Retry-After เมื่อกลับมา การปฏิบัติการของซ็อกเก็ตโดยใช้ 120- หมดเวลาที่สอง โฟลเดอร์ตัวอย่างที่มีอยู่หยุดการทํางาน ก่อนที่จะส่งการร้องขอ

measure.py
import hashlib
import json
import os
import platform
import sys
import time
from datetime import datetime, timezone
from http.client import HTTPException
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

if len(sys.argv) != 4:
    raise SystemExit("Usage: python measure.py request.json NEW_DIRECTORY CLIENT_REGION")
key = os.environ.get("FLASHDATA_API_KEY")
if not key:
    raise SystemExit("Set FLASHDATA_API_KEY first")
payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig"))
if not isinstance(payload, dict) or payload.get("source") != "google_search" \
        or set(payload) - {"source", "query", "params"} \
        or not isinstance(payload.get("query"), str) or not payload["query"].strip() \
        or not isinstance(payload.get("params", {}), dict):
    raise SystemExit("This example measures one realtime google_search request")
body = json.dumps(payload, sort_keys=True, allow_nan=False).encode()
settings = json.dumps({"source": payload["source"], "params": payload.get("params", {})},
    sort_keys=True, allow_nan=False).encode()
folder = Path(sys.argv[2])
try:
    folder.mkdir(mode=0o700)
except FileExistsError:
    raise SystemExit("Sample directory already exists; no request sent. Inspect its saved files.")
(folder / "request.json").write_bytes(body)
request = Request("https://data.flashdata.dev/v1/queries/realtime", data=body,
    headers={"X-API-Key": key, "Content-Type": "application/json", "Accept": "application/json"})
report = {"started_at": datetime.now(timezone.utc).isoformat(),
    "region": sys.argv[3], "source": payload["source"], "mode": "realtime",
    "input_sha256": hashlib.sha256(body).hexdigest(),
    "settings_sha256": hashlib.sha256(settings).hexdigest(), "concurrency": 1,
    "python_version": platform.python_version(), "timeout_seconds": 120,
    "http_status": None, "request_id": None, "retry_after": None,
    "elapsed_ms": None, "outcome": "unknown"}
(folder / "timing.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
raw = b""
start = time.perf_counter()
try:
    try:
        response = build_opener(NoRedirect()).open(request, timeout=120)
    except HTTPError as error:
        response = error
    with response:
        report["http_status"] = response.status
        report["request_id"] = response.headers.get("X-Request-Id")
        report["retry_after"] = response.headers.get("Retry-After")
        raw = response.read()
except (URLError, OSError, HTTPException):
    report["error"] = "transport_error_or_timeout"
report["elapsed_ms"] = round((time.perf_counter() - start) * 1000, 3)
try:
    result = json.loads(raw)
except (ValueError, UnicodeDecodeError):
    result = {}
if report["http_status"] is not None and "error" not in report:
    complete = report["http_status"] == 200 and isinstance(result, dict) \
        and result.get("status") == "done" and isinstance(result.get("results"), list)
    report["outcome"] = "completed" if complete else "failed"
(folder / "response.json").write_bytes(raw)
(folder / "timing.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(json.dumps(report, indent=2))
raise SystemExit(0 if report["outcome"] == "completed" else 1)

ประมวลผลและตรวจสอบ

แทนที่การแทนที่ลูกค้าด้วยขอบเขตเครื่องลูกความของคุณ เช่น ยูโร-เวสต์1. ประมวลผลคําสั่งตัวแรกหนึ่งครั้ง; คําสั่งที่สองจะอ่านเฉพาะเวลาที่บันทึกไว้เท่านั้น

การค้นหาหนึ่ง แล้วอ่านภายใน
python measure.py request.json sample-01 client-region
python -m json.tool sample-01/timing.json

ตรวจสอบแฟ้มบันทึก

การ ออก แบบ ที่ ประสบ ผล สําเร็จ พร้อม กับ รหัส 0 และบันทึก http_status: 200 ถึง outcome: completed. ร่างกายตอบสนองมี status: done และอาร์เรย์ผลลัพธ์ ล้มเหลวหรือไม่รู้จักทางออกที่มีรหัส 1สืบค้นแฟ้มก่อนที่จะตัดสินใจอีกครั้ง

แฟ้มต้องตรวจสอบอะไร
sample-01/request.jsonค่าที่ป้อนได้พอดี บันทึกไว้ก่อนที่จะส่ง
sample-01/response.jsonร่างตอบสนองแบบ Raw; HTTP ความผิดพลาดอาจส่งกลับที่ไม่ใช่-JSON เนื้อหา
sample-01/timing.jsonelapsed_msผล http_status, request_id ถึง retry_after. A null elapsed_ms หมายความว่าโพรเซสไม่ได้ทํางานอยู่ finish บันทึกเสียง

3. ผลรวมตัวอย่างที่บันทึกไว้

บันทึก summarize.py ข้าง measure.py. มันจะอ่านตัวอย่างภายในเครื่อง และปฏิเสธโฟลเดอร์ที่ซ้ํากัน, เวลาไม่สมบูรณ์ และการตั้งค่าที่ต้องการที่ไม่เหมาะสม, ขอบเขตไคลเอนต์ หรือ Python เวอร์ชั่น

p50/p95 ใช้ค่าเปอร์เซ็นต์ที่ใกล้ที่สุดจากการตอบสนองที่เสร็จสมบูรณ์ ล้มเหลวและล้มเหลว การพยายามที่ไม่ทราบยังคงอยู่ในทั้งหมด ตัวอย่างที่ประสบความสําเร็จหนึ่งให้ p50 กับ p95 เดียวกัน; ไม่มีตัวอย่างที่สําเร็จให้ null ทั้ง 2 ตัว

summarize.py
import json
import math
import sys
from pathlib import Path

if len(sys.argv) < 2:
    raise SystemExit("Usage: python summarize.py SAMPLE_DIRECTORY [SAMPLE_DIRECTORY ...]")
folders = [Path(value).resolve() for value in sys.argv[1:]]
if len(set(folders)) != len(folders):
    raise SystemExit("Pass each sample directory only once")
rows = [json.loads((folder / "timing.json").read_text(encoding="utf-8")) for folder in folders]
fields = ("source", "mode", "region", "concurrency", "timeout_seconds", "settings_sha256", "python_version")
for row in rows:
    if not isinstance(row, dict) or any(field not in row for field in (*fields, "input_sha256")):
        raise SystemExit("Use timing.json files written by this measure.py")
    elapsed = row.get("elapsed_ms")
    if row.get("outcome") not in ("completed", "failed", "unknown") \
            or type(elapsed) not in (int, float) or not math.isfinite(elapsed) or elapsed < 0:
        raise SystemExit("Incomplete or invalid timing record; inspect it before summarizing")
if len({json.dumps([row[field] for field in fields], sort_keys=True) for row in rows}) != 1:
    raise SystemExit("Compare runs separately when source, mode, region or settings differ")
times = sorted(row["elapsed_ms"] for row in rows if row["outcome"] == "completed")
inputs = len({row["input_sha256"] for row in rows})
def percentile(percent):
    return times[math.ceil(len(times) * percent / 100) - 1] if times else None
print(json.dumps({"context": {field: rows[0][field] for field in fields},
    "attempted": len(rows), "completed": len(times),
    "failed": sum(row["outcome"] == "failed" for row in rows),
    "unknown": sum(row["outcome"] == "unknown" for row in rows),
    "success_rate": len(times) / len(rows), "distinct_inputs": inputs,
    "input_pattern": "repeated_input" if inputs == 1 else "varied_inputs",
    "successful_latency_ms": {"p50": percentile(50), "p95": percentile(95)}}, indent=2))
อ่านตัวอย่างแรก
python summarize.py sample-01

เพิ่มตัวอย่างโดยเจตนา

คําสั่งแรกที่ด้านล่างส่งหนึ่งการค้นหาเพิ่มเติม เก็บค่าไคลเอนต์และการตั้งค่าที่ต้องการไว้ เพื่อวัดค่าข้อมูลต่าง ๆ การเปลี่ยนแปลงเฉพาะการสอบถามเท่านั้น request.json ก่อนที่จะดําเนินการมัน รายงานนี้ระบุรูปแบบการนําเข้า และนับค่าต่าง ๆ ที่ป้อนเข้าไป

สําหรับการประเมินตัวแทน-รัน เห็นด้วยกับจํานวนตัวอย่าง และงบประมาณเครดิตก่อน ประมวลผลตัวอย่างอย่างต่ํา; ตัวอย่างนี้บันทึกความต่อเนื่อง: 1 บันทึกส่วนสรุปด้วยโฟลเดอร์ตัวอย่าง

การค้นหาเพิ่มเติมหนึ่งรายการ
python measure.py request.json sample-02 client-region
Akregator บันทึกตัวอย่างไว้ ไม่ต้องการใหม่
python summarize.py sample-01 sample-02 > summary.json
python -m json.tool summary.json

วัดการส่งสื่อด้วย CLI

ตัวอย่างนี้แยกส่งหนึ่ง MP3 ไปยังห้องเก็บของของคุณ ติดตั้ง CLIใช้โพรไฟล์เจ้าของที่บันทึกไว้ youtube_download อนุญาต และรักษาไดเรกทอรีสถานะเอาไว้ ตัวจับเวลาใช้ค่าโพรไฟล์ดังกล่าวซ้ํา และไม่สนใจ FLASHDATA_API_KEY ใช้งานตัวพิมพ์ใหญ่สําหรับดาวน์โหลดปกติ

ในแฟลชดาต้า- Benchar/ บันทึกปลายทางของคุณเป็น storage.json นี่ S3 ตัวอย่างต้องการถังของคุณ พื้นที่และเอกสารรับรองการจัดเก็บ ใช้แฟ้มส่วนตัวที่มีอยู่แล้ว หากคุณมีอยู่แล้ว

storage.json
{
  "storage_type": "s3",
  "storage_url": "YOUR_BUCKET",
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "region": "us-east-1"
}

บันทึกเวลาส่ง

บันทึก measure-download.py ข้าง storage.json. มันช่วยรักษาการวิ่งใหม่ ID ก่อนจะเริ่ม CLIรอคอยต่อไป 10 นาทีสําหรับคําสั่ง และบันทึกเวลาหลังการส่งออก การหยุดโฟลเดอร์ตัวอย่างก่อนจะทําการเรียก CLI

measure-download.py
import json
import os
import shutil
import subprocess
import sys
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path

if len(sys.argv) not in (6, 7):
    raise SystemExit("Usage: python measure-download.py VIDEO_ID storage.json NEW_DIRECTORY PROFILE CLIENT_REGION [STATE_DIRECTORY]")
video, storage, directory, profile, region = sys.argv[1:6]
binary = shutil.which("flashdata")
if not binary or not Path(storage).is_file():
    raise SystemExit("Install flashdata on PATH and create the private storage.json first")
folder = Path(directory)
try:
    folder.mkdir(mode=0o700)
except FileExistsError:
    raise SystemExit("Sample directory already exists; inspect timing.json and recover its run_id.")
report = {"run_id": "perf-" + uuid.uuid4().hex, "profile": profile,
    "started_at": datetime.now(timezone.utc).isoformat(),
    "source": "youtube_download", "video_id": video, "output_format": "mp3",
    "region": region, "metric": "cli_start_to_result_saved",
    "timeout_seconds": 600, "elapsed_seconds": None, "outcome": "unknown"}
timing = folder / "timing.json"
timing.write_text(json.dumps(report, indent=2), encoding="utf-8")
print("Saved run_id in " + str(timing), flush=True)
command = [binary, "youtube", "download", video, "--format", "mp3",
    "--storage-config", str(Path(storage).resolve()), "--mode", "async", "--wait",
    "--run-id", report["run_id"], "--output", str(folder / "delivery.json"),
    "--profile", profile, "--timeout", "10m", "--json", "--non-interactive"]
if len(sys.argv) == 7:
    report["state_directory"] = str(Path(sys.argv[6]).resolve())
    command.extend(["--state-dir", report["state_directory"]])
    timing.write_text(json.dumps(report, indent=2), encoding="utf-8")
environment = dict(os.environ)
environment.pop("FLASHDATA_API_KEY", None)  # Reuse the named profile's stored key.
start = time.perf_counter()
with (folder / "cli.json").open("wb") as output, (folder / "cli-error.json").open("wb") as errors:
    try:
        completed = subprocess.run(command, env=environment, stdout=output, stderr=errors,
            timeout=620, check=False)
        report["exit_code"] = completed.returncode
        report["outcome"] = "completed" if completed.returncode == 0 else "not_completed"
    except (OSError, subprocess.TimeoutExpired):
        report["error"] = "process_error_or_timeout"
report["elapsed_seconds"] = time.perf_counter() - start
timing.write_text(json.dumps(report, indent=2), encoding="utf-8")
print(json.dumps(report, indent=2))
raise SystemExit(0 if report["outcome"] == "completed" else 1)

ประมวลผลหนึ่งการส่ง

แทนที่งานวิจัยด้วยชื่อโปรไฟล์ที่บันทึกไว้ของคุณ และค่าลูกค้ากับขอบเขตของเครื่องนี้ วิดีโอ ID สามารถแทนที่ได้โดยหนึ่งตัวที่คุณสามารถประมวลผลได้ การบันทึกการทํางานเสร็จสมบูรณ์ download-01/delivery.json, timing.json ถึง CLI แฟ้มส่งออก

คําสั่งใช้ CLIไดเรกทอรีสถานะปริยาย หากโพรไฟล์ของคุณใช้ไดเรกทอรีกําหนดเอง ให้ทําการเพิ่มพาธของมันเป็นอาร์กิวเมนต์ตัวสุดท้าย หลังจากไคลเอนต์ลบแล้ว

การส่ง MP3 หนึ่งเครื่อง
python measure-download.py jNQXAC9IVRw storage.json download-01 research client-region
python -m json.tool download-01/timing.json

คํานวณผลลัพธ์การบันทึกแบบผ่าน ๆ

บันทึก throughput.py ในแฟลชดาต้า- Benchar/, ข้าง ๆ measure-download.py. มันอ่านค่าการส่งและจับเวลาที่เสร็จสมบูรณ์แล้วจากการดาวน์โหลด- 01/โดยไม่ส่งการร้องขอ การนําสื่อผ่านเป็นผลรวมของสื่อ file_size ค่าหารด้วย elapsed_seconds; ไบต์ 8 ○ วินาที 1,000,000.

throughput.py
import json
import math
import sys
from pathlib import Path

if len(sys.argv) != 2:
    raise SystemExit("Usage: python throughput.py SAMPLE_DIRECTORY")
folder = Path(sys.argv[1])
timing = json.loads((folder / "timing.json").read_text(encoding="utf-8"))
if not isinstance(timing, dict) or timing.get("outcome") != "completed" \
        or timing.get("metric") != "cli_start_to_result_saved":
    raise SystemExit("Use a completed sample from measure-download.py")
elapsed = timing.get("elapsed_seconds")
if type(elapsed) not in (int, float) or not math.isfinite(elapsed) or elapsed <= 0:
    raise SystemExit("Missing or invalid elapsed_seconds")
result = json.loads((folder / "delivery.json").read_text(encoding="utf-8-sig"))
if not isinstance(result, dict) or result.get("status") not in ("done", "completed") \
        or result.get("source") != "youtube_download":
    raise SystemExit("Use the completed download result, not a submission or job-status response")
files = result.get("results")
if not isinstance(files, list) or not files or any(not isinstance(item, dict) for item in files):
    raise SystemExit("No delivered media records")
sizes = [item.get("file_size") for item in files]
if any(type(size) not in (int, float) or not math.isfinite(size) or size <= 0 for size in sizes):
    raise SystemExit("Missing or invalid media file_size")
total = sum(sizes)
print(json.dumps({"run_id": timing["run_id"], "metric": timing["metric"],
    "delivered_media_bytes": total, "elapsed_seconds": elapsed,
    "bytes_per_second": total / elapsed, "megabits_per_second": total * 8 / elapsed / 1_000_000}, indent=2))
อ่านค่าวัดที่บันทึกไว้
python throughput.py download-01

ถ้าการส่งไม่ได้ finish

อ่าน download-01/cli-error.json และ run_id ใน timing.json. ใช้ runs show ถึง runs recover กับที่ ID และประวัติเดิม การกู้ข้อมูลการรับงานที่ยอมรับแล้ว; เก็บความพยายามนี้ออกจากผลรวมที่เสร็จโดยผ่านระบบ แทนที่จะรีสตาร์ทตัวจับเวลา หรือส่งการดาวน์โหลดอื่น ๆ

แสดงเฉพาะความพยายามที่บันทึกไว้
python -m json.tool download-01/timing.json
python -c "from pathlib import Path; print(Path('download-01/cli-error.json').read_text(encoding='utf-8'))"

รายงาน Bulk ชุดสะสม

Sum file_size สําหรับบันทึกสื่อที่เสร็จสมบูรณ์ และหารด้วยช่วงเวลาต่าง ๆ ของการเก็บรวบรวม ตอบรับการบันทึก การนับที่เสร็จและล้มเหลว การสํารวจทุกช่วงเวลา และหยุดชั่วคราว คงแหล่งไว้ IDs, ตัวเลือกการแสดงผล และขอบเขตปลายทางที่มีรายงานนี้ การกู้สื่อจากถังของคุณ เป็นการวัดแยกต่างหาก