Skip to content

Python : Floating-Point Representation Performance Benchmark Suite - #351

Merged
kimpro82 merged 11 commits into
masterfrom
pyFloatingType
Aug 28, 2026
Merged

Python : Floating-Point Representation Performance Benchmark Suite#351
kimpro82 merged 11 commits into
masterfrom
pyFloatingType

Conversation

@kimpro82

Copy link
Copy Markdown
Owner

Floating-Point Type and Python/NumPy Conversion Benchmark (2026.08.27)

  • Overview

    • A comparison of memory usage and execution speed for Python float, decimal.Decimal, NumPy float32, and NumPy float64.
    • The benchmark also measures the overhead of repeatedly converting between Python lists and NumPy arrays.
  • Components

    • floating.py: Creates the datasets, measures memory and execution time, and prints the comparison report.
    • run.py: A helper script that reads dependencies.yaml, installs configured packages, and runs the selected Python script.
    • dependencies.yaml: Registers numpy and pympler as dependencies for floating.py.
  • Measurements

    • Memory usage includes nested objects and container overhead measured with pympler.asizeof.asizeof.
    • Numeric operations multiply every value by 1.05. Python lists use list comprehensions, while NumPy arrays use vectorized multiplication.
    • The conversion benchmark compares direct NumPy operation, Python list operation, list-to-NumPy conversion, NumPy-to-list conversion, and a complete list/NumPy round trip.
    • Conversion costs are included in each timed statement, showing why repeated representation changes can remove the benefit of NumPy.
  • Execution Commands and Results

    $ python3 run.py floating.py
    --- Running 'floating.py' ---
    
    === [Benchmark Report] Data Size: 10,000 elements ===
    
    === [Numeric Type Benchmark] ===                             === [Python/NumPy Conversion Overhead] ===
    Data Type          | Memory (Bytes)  | Execution Time (s)    Operation                    | Execution Time (s)
    ----------------------------------------------------------   --------------------------------------------------
    Python float       |         325,176 |            0.32852    NumPy direct operation       |            0.00264
    Decimal            |       1,125,176 |            3.15240    Python list operation        |            0.28159
    NumPy float32      |          40,128 |            0.00204    List to NumPy each time      |            0.32939
    NumPy float64      |          80,128 |            0.00272    NumPy to list each time      |            0.16725
                                                                 List-NumPy round trip        |            0.58042

    Execution times vary by machine and system load. The important observation is that direct NumPy operations are fast, but repeatedly converting between lists and arrays can make the combined operation slower than staying with a Python list. A practical approach is to convert data once, perform multiple operations while it remains a NumPy array, and convert it back only when necessary.

@kimpro82

kimpro82 commented Aug 27, 2026

Copy link
Copy Markdown
Owner Author

Answer from Github Copilot

DB에서 값이 수시로 바뀌고, 매번 필요한 값만 개별적으로 조회해서 즉시 연산한다면 NumPy를 사용하지 않고 Python의 스칼라 타입으로 처리하는 것이 일반적으로 적절합니다.

다만 “항상 Python float만 사용한다”기보다는 DB 컬럼의 타입과 필요한 정밀도에 맞춰 Python 타입을 선택한다고 보는 편이 정확합니다.

일반적인 선택

DB 저장 타입 Python에서 주로 받는 타입 적합한 경우
FLOAT, REAL, DOUBLE float 근삿값이면 충분한 센서값, 통계값, 과학 계산
DECIMAL, NUMERIC Decimal 금액, 비율, 정산값처럼 10진수 정밀도가 중요한 경우
정수로 스케일링한 값 int 소수 둘째 자리 등을 명확히 고정할 수 있는 경우

예를 들어 DB에 다음과 같이 저장되어 있다면:

price DECIMAL(12, 2)

Python에서 Decimal로 받는 것이 맞을 가능성이 높습니다.

price = row["price"]
taxed_price = price * Decimal("1.1")

반면 다음처럼 근삿값 저장이 의도라면:

temperature DOUBLE

Python float로 받아 계산하는 것이 자연스럽습니다.

temperature = row["temperature"]
adjusted_temperature = temperature * 1.05

NumPy가 적합하지 않은 이유

값을 하나씩 조회하는 흐름이 다음과 같다고 가정하면:

DB 조회
 -> Python 값 하나 반환
 -> 계산
 -> 결과 저장 또는 반환

여기에 NumPy를 넣으면:

DB 조회
 -> Python 값 하나 반환
 -> 1개짜리 NumPy 배열로 변환
 -> NumPy 연산
 -> Python 값으로 변환

이 됩니다.

데이터가 하나뿐이면 NumPy의 벡터화 이점이 없습니다. 오히려 배열 생성과 변환 비용만 추가됩니다.

value = float(row["value"])
result = value * 1.05

이런 방식이 더 단순하고 적절합니다.

중요한 점: DB 조회 비용이 훨씬 큼

이 경우 성능의 주요 비용은 대개 자료형 연산보다 다음 부분입니다.

DB 네트워크 통신
쿼리 실행
인덱스 탐색
행 변환
트랜잭션 처리

float 곱셈과 NumPy 배열 생성 비용을 비교하기 전에, DB를 매번 조회하는 비용이 훨씬 클 가능성이 높습니다. 따라서 NumPy를 사용하지 않는 판단은 합리적이지만, 실제 성능 개선은 다음에서 더 크게 발생할 수 있습니다.

  • 필요한 컬럼만 조회
  • 적절한 인덱스 사용
  • 불필요한 반복 조회 줄이기
  • 같은 요청 안에서 중복 조회 방지
  • 가능하면 계산을 SQL에서 수행
  • 트랜잭션과 연결 관리 최적화

DB에서 계산하는 방법도 있음

단순한 계산이라면 DB에서 바로 처리할 수도 있습니다.

SELECT value * 1.05 AS adjusted_value
FROM measurements
WHERE id = ?;

이 경우 Python에서는 계산 결과만 받습니다. 다만 복잡한 계산이거나 DB와 애플리케이션 사이에서 계산 책임을 분리해야 한다면 Python에서 처리하는 편이 나을 수 있습니다.

최종 결론

현재 조건이라면:

DB에서 값을 개별적으로 조회하고, 조회한 값으로 한두 번 계산한 뒤 버리는 구조라면 NumPy를 사용하지 않는 것이 맞다.

다만:

정밀도가 중요하면 Python float가 아니라 Decimal을 사용해야 한다.

즉, 추천 기준은 다음과 같습니다.

대량 데이터를 한꺼번에 가져와 반복 계산
    -> NumPy 고려

값을 하나씩 조회해 즉시 계산
    -> Python float 또는 Decimal

금액/정확한 소수 계산
    -> DB DECIMAL/NUMERIC + Python Decimal

근삿값 계산
    -> DB DOUBLE/FLOAT + Python float

따라서 사용자의 상황에서는 NumPy를 제외하는 판단은 타당하지만, float를 선택할지는 DB 저장 타입과 정밀도 요구사항을 기준으로 결정해야 합니다.

@kimpro82
kimpro82 marked this pull request as ready for review August 27, 2026 12:49
@kimpro82
kimpro82 requested a lite review from Copilot August 27, 2026 12:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new runner’s dependency lookup and script path handling are brittle when invoked outside Python/, and the Decimal benchmark timing currently includes avoidable constant-construction overhead that skews results.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Adds a small benchmark suite under Python/ to compare memory/time characteristics of Python numeric types vs NumPy arrays, plus a helper runner that installs per-script dependencies defined in YAML.

Changes:

  • Add Python/floating.py benchmark for float/Decimal/NumPy types and list↔NumPy conversion overhead.
  • Add Python/run.py + Python/dependencies.yaml to auto-install benchmark dependencies before execution.
  • Update root and Python READMEs to link and document the new benchmark.
File summaries
File Description
README.md Adds an entry linking to the new benchmark section in Python/README.md.
Python/run.py New script runner that reads dependencies.yaml, installs packages, then runs a target script.
Python/README.md Documents the new benchmark and shows sample invocation/output.
Python/floating.py Implements memory/time benchmarks across Python/Decimal/NumPy and conversion overhead measurements.
Python/dependencies.yaml Declares numpy and pympler as dependencies for floating.py.
Review details
  • Files reviewed: 5/5 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread Python/run.py
Comment thread Python/run.py
Comment thread Python/floating.py

@kimpro82 kimpro82 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Aspect Details
Title Python : Floating-Point Representation Performance Benchmark Suite
Author kimpro82 (PR owner)
State Open (not draft)
Files Changed 5 files
Lines Added/Deleted +283 / -0
Commits 11
Comments 1
Review Comments 3
Mergeable Yes (clean state)
CI Status No CI checks shown

Key Changes

  • Python/floating.py — Main benchmark script measuring memory and execution time for numeric types and list/array conversion overhead
  • Python/run.py — New dependency runner that reads a YAML config, installs packages, and executes target scripts
  • Python/dependencies.yaml — Registers numpy and pympler dependencies for the benchmark
  • README.md & Python/README.md — Updated with links and documentation for the new benchmark

Review Status

A Copilot review flagged 2 issues to address:

  1. Brittle path handling in the runner when called outside Python/ directory
  2. Constant overhead in Decimal timing — Decimal object construction is included in the benchmark and skews results

Want me to

  1. Review the specific comments on the PR to see the detailed feedback
  2. Examine the file changes to understand the benchmark implementation details
  3. Help address the review issues flagged by Copilot

@kimpro82
kimpro82 merged commit a43675e into master Aug 28, 2026
@kimpro82
kimpro82 deleted the pyFloatingType branch August 28, 2026 15:04
@kimpro82 kimpro82 moved this from In Progress to Done in My Python Practice Aug 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Development

Successfully merging this pull request may close these issues.

Python : Floating-Point Representation Performance Benchmark Suite

2 participants