최적화
최적화 (Optimizations)
지연(lazy) 평가와 즉시(eager) 평가의 차이를 앞서 간단히 다뤘어요. 이 페이지에서는 lazy API를 사용해 엄청난 성능 이점을 얻는 방법을 보여드릴게요.
출처: 문서
본문
Lazy vs Eager
Polars는 lazy와 eager 두 가지 실행 모드를 지원해요. eager API에서는 쿼리가 즉시 실행되지만, lazy API에서는 쿼리가 '필요할 때'에만 평가돼요. 실행을 최대한 미루는 것은 상당한 성능 이점을 가질 수 있고, 그래서 대부분의 비대화형(non-interactive) 경우에 lazy API가 선호돼요.
예시
이전 페이지의 예시를 사용해 lazy API 사용의 성능 이점을 보여드릴게요. 아래 코드는 archive.org에서의 업로드 수를 계산해요.
Eager
import polars as pl
import datetime
df = pl.read_csv("hf://datasets/commoncrawl/statistics/tlds.csv", try_parse_dates=True)
df = df.select("suffix", "crawl", "date", "tld", "pages", "domains")
df = df.filter(
(pl.col("date") >= datetime.date(2020, 1, 1)) |
pl.col("crawl").str.contains("CC")
)
df = df.with_columns(
(pl.col("pages") / pl.col("domains")).alias("pages_per_domain")
)
df = df.group_by("tld", "date").agg(
pl.col("pages").sum(),
pl.col("domains").sum(),
)
df = df.group_by("tld").agg(
pl.col("date").unique().count().alias("number_of_scrapes"),
pl.col("domains").mean().alias("avg_number_of_domains"),
pl.col("pages").sort_by("date").pct_change().mean().alias("avg_page_growth_rate"),
).sort("avg_number_of_domains", descending=True).head(10)
Lazy
import polars as pl
import datetime
lf = (
pl.scan_csv("hf://datasets/commoncrawl/statistics/tlds.csv", try_parse_dates=True)
.filter(
(pl.col("date") >= datetime.date(2020, 1, 1)) |
pl.col("crawl").str.contains("CC")
).with_columns(
(pl.col("pages") / pl.col("domains")).alias("pages_per_domain")
).group_by("tld", "date").agg(
pl.col("pages").sum(),
pl.col("domains").sum(),
).group_by("tld").agg(
pl.col("date").unique().count().alias("number_of_scrapes"),
pl.col("domains").mean().alias("avg_number_of_domains"),
pl.col("pages").sort_by("date").pct_change().mean().alias("avg_page_growth_rate"),
).sort("avg_number_of_domains", descending=True).head(10)
)
df = lf.collect()
실행 시간 (Timings)
일반적인 노트북과 가정용 인터넷 연결에서 두 쿼리를 실행한 결과는 다음과 같아요:
- Eager:
1.96초 - Lazy:
410밀리초
lazy 쿼리는 eager보다 약 5배 빠르죠. 그 이유는 쿼리 최적화기 때문이에요: collect를 끝까지 미루면 Polars는 어떤 컬럼과 행이 필요한지 추론하고, 데이터를 읽을 때 가능한 한 일찍 필터를 적용할 수 있어요. 특정 행 그룹의 min, max 같은 메타데이터를 포함하는 Parquet 같은 파일 형식의 경우, Polars가 데이터를 네트워크로 전송하지 않고 필터와 메타데이터만으로 전체 행 그룹을 건너뛸 수 있기 때문에 차이가 더 커질 수 있어요.
더 알아보기 (Learn more)
- 허브에서 Polars 사용하기 문서에서 Polars와 허브의 기본을 배울 수 있어요.
- Polars 공식 문서에서 lazy API의 모든 기능을 확인하세요.