NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Middle85 views

# Парсинг и сохранение в БД занимает ~10 секунд parse_text_and_save_to_postgres(text_data)

Practice

AI answer

First, I would measure the time spent on each stage separately: parsing, data preparation, and writing to PostgreSQL. time.perf_counter() and a profiler are suitable for this; optimizing without measurements is risky.

If writing is the bottleneck, it usually helps to avoid executing an INSERT for each record individually: prepare the rows and insert them in batches within a single transaction. For large volumes of data, COPY is often more efficient in PostgreSQL. It is also worth checking the query plan and indexes, but don’t add indexes blindly: they speed up reads but slow down writes.

import time

start = time.perf_counter()
rows = parse(text_data)
parsed_at = time.perf_counter()

with conn.cursor() as cur:
    cur.executemany(
        "INSERT INTO records (field_a, field_b) VALUES (%s, %s)",
        [(row.field_a, row.field_b) for row in rows],
    )
conn.commit()

print(f"parse={parsed_at - start:.2f}s, save={time.perf_counter() - parsed_at:.2f}s")

If parsing itself is slow, profile it separately and optimize the most expensive operations. After making changes, compare the time using the same amount of data and verify that the results are correct.

Also asked at GigaChat / Сбер

Similar questions