Skip to content

Instantly share code, notes, and snippets.

@charsyam
Created July 14, 2025 13:14
Show Gist options
  • Save charsyam/60d67a4fc45199785f5a0d3a5e87f182 to your computer and use it in GitHub Desktop.
Save charsyam/60d67a4fc45199785f5a0d3a5e87f182 to your computer and use it in GitHub Desktop.
import pymysql
import time
import random
import string
# MySQL 연결 설정 - 본인의 디비서버 설정을 추가하자.
DB_CONFIG = {
"host": "",
"user": "",
"password": "",
"database": "",
"autocommit": True,
}
# 입력할 데이터 수
NUM_ROWS = 10000
BATCH_SIZE = 1000
# 무작위 문자열 생성 함수
def random_string(length=10):
return "".join(random.choices(string.ascii_letters, k=length))
# 테스트용 데이터 생성
def generate_data(n):
return [(random_string(10),) for _ in range(n)]
# 단건 insert 테스트
def insert_single(cursor, data):
for row in data:
cursor.execute("INSERT INTO tests(name) VALUES (%s)", row)
# 배치 insert 테스트
def insert_batch(cursor, data, batch_size):
for i in range(0, len(data), batch_size):
batch = data[i : i + batch_size]
cursor.executemany("INSERT INTO tests(name) VALUES (%s)", batch)
# 메인 실행 함수
def main():
conn = pymysql.connect(**DB_CONFIG)
cur = conn.cursor()
print("💡 Truncating table...")
cur.execute("TRUNCATE TABLE tests")
print("📌 Inserting single rows...")
data = generate_data(NUM_ROWS)
start = time.time()
insert_single(cur, data)
elapsed_single = time.time() - start
print(f"⏱️ Single insert time: {elapsed_single:.2f} seconds")
cur.execute("TRUNCATE TABLE tests")
print("📌 Inserting with batch...")
data = generate_data(NUM_ROWS)
start = time.time()
insert_batch(cur, data, BATCH_SIZE)
elapsed_batch = time.time() - start
print(
f"⏱️ Batch insert time (batch size {BATCH_SIZE}): {elapsed_batch:.2f} seconds"
)
cur.close()
conn.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment