forked from duckdb/duckdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regression_test_python.py
402 lines (329 loc) · 12.7 KB
/
regression_test_python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import os
import sys
import duckdb
import pandas as pd
import pyarrow as pa
import time
import argparse
from typing import Dict, List, Any
import numpy as np
TPCH_QUERIES = []
res = duckdb.execute(
"""
select query from tpch_queries()
"""
).fetchall()
for x in res:
TPCH_QUERIES.append(x[0])
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true", help="Enable verbose mode", default=False)
parser.add_argument("--threads", type=int, help="Number of threads", default=None)
parser.add_argument("--nruns", type=int, help="Number of runs", default=10)
parser.add_argument("--out-file", type=str, help="Output file path", default=None)
parser.add_argument("--scale-factor", type=float, help="Set the scale factor TPCH is generated at", default=1.0)
args, unknown_args = parser.parse_known_args()
verbose = args.verbose
threads = args.threads
nruns = args.nruns
out_file = args.out_file
scale_factor = args.scale_factor
if unknown_args:
parser.error(f"Unrecognized parameter(s): {', '.join(unknown_args)}")
def print_msg(message: str):
if not verbose:
return
print(message)
def write_result(benchmark_name, nrun, t):
bench_result = f"{benchmark_name}\t{nrun}\t{t}"
if out_file is not None:
if not hasattr(write_result, 'file'):
write_result.file = open(out_file, 'w+')
write_result.file.write(bench_result)
write_result.file.write('\n')
else:
print_msg(bench_result)
def close_result():
if not hasattr(write_result, 'file'):
return
write_result.file.close()
class BenchmarkResult:
def __init__(self, name):
self.name = name
self.runs: List[float] = []
def add(self, duration: float):
self.runs.append(duration)
def write(self):
for i, run in enumerate(self.runs):
write_result(self.name, i, run)
class TPCHData:
TABLES = ["customer", "lineitem", "nation", "orders", "part", "partsupp", "region", "supplier"]
def __init__(self, scale_factor):
self.conn = duckdb.connect()
self.conn.execute(f'CALL dbgen(sf={scale_factor})')
def get_tables(self, convertor) -> Dict[str, Any]:
res = {}
for table in self.TABLES:
res[table] = convertor(self.conn, table)
return res
def load_lineitem(self, collector, benchmark_name) -> BenchmarkResult:
query = 'SELECT * FROM lineitem'
result = BenchmarkResult(benchmark_name)
for _ in range(nruns):
duration = 0.0
start = time.time()
rel = self.conn.sql(query)
res = collector(rel)
end = time.time()
duration = float(end - start)
del res
padding = " " * len(str(nruns))
print_msg(f"T{padding}: {duration}s")
result.add(duration)
return result
class TPCHBenchmarker:
def __init__(self, name: str):
self.initialize_connection()
self.name = name
def initialize_connection(self):
self.con = duckdb.connect()
if not threads:
return
print_msg(f'Limiting threads to {threads}')
self.con.execute(f"SET threads={threads}")
def register_tables(self, tables: Dict[str, Any]):
for name, table in tables.items():
self.con.register(name, table)
def run_tpch(self, collector, benchmark_name) -> BenchmarkResult:
print_msg("")
print_msg(TPCH_QUERIES)
result = BenchmarkResult(benchmark_name)
for _ in range(nruns):
duration = 0.0
# Execute all queries
for i, query in enumerate(TPCH_QUERIES):
start = time.time()
rel = self.con.sql(query)
if rel:
res = collector(rel)
del res
else:
print_msg(f"Query '{query}' did not produce output")
end = time.time()
query_time = float(end - start)
print_msg(f"Q{str(i).ljust(len(str(nruns)), ' ')}: {query_time}")
duration += float(end - start)
padding = " " * len(str(nruns))
print_msg(f"T{padding}: {duration}s")
result.add(duration)
return result
def test_tpch():
print_msg(f"Generating TPCH (sf={scale_factor})")
tpch = TPCHData(scale_factor)
## -------- Benchmark converting LineItem to different formats ---------
def fetch_native(rel: duckdb.DuckDBPyRelation):
return rel.fetchall()
def fetch_pandas(rel: duckdb.DuckDBPyRelation):
return rel.df()
def fetch_arrow(rel: duckdb.DuckDBPyRelation):
return rel.arrow()
COLLECTORS = {'native': fetch_native, 'pandas': fetch_pandas, 'arrow': fetch_arrow}
# For every collector, load lineitem 'nrun' times
for collector in COLLECTORS:
result: BenchmarkResult = tpch.load_lineitem(COLLECTORS[collector], collector + "_load_lineitem")
print_msg(result.name)
print_msg(collector)
result.write()
## ------- Benchmark running TPCH queries on top of different formats --------
def convert_pandas(conn: duckdb.DuckDBPyConnection, table_name: str):
return conn.execute(f"SELECT * FROM {table_name}").df()
def convert_arrow(conn: duckdb.DuckDBPyConnection, table_name: str):
df = convert_pandas(conn, table_name)
return pa.Table.from_pandas(df)
CONVERTORS = {'pandas': convert_pandas, 'arrow': convert_arrow}
# Convert TPCH data to the right format, then run TPCH queries on that data
for convertor in CONVERTORS:
tables = tpch.get_tables(CONVERTORS[convertor])
tester = TPCHBenchmarker(convertor)
tester.register_tables(tables)
collector = COLLECTORS[convertor]
result: BenchmarkResult = tester.run_tpch(collector, f"{convertor}tpch")
result.write()
def generate_string(seed: int):
output = ''
for _ in range(10):
output += chr(ord('A') + int(seed % 26))
seed /= 26
return output
class ArrowDictionary:
def __init__(self, unique_values):
self.size = unique_values
self.dict = [generate_string(x) for x in range(unique_values)]
class ArrowDictionaryBenchmark:
def __init__(self, unique_values, values, arrow_dict: ArrowDictionary):
assert unique_values <= arrow_dict.size
self.initialize_connection()
self.generate(unique_values, values, arrow_dict)
def initialize_connection(self):
self.con = duckdb.connect()
if not threads:
return
print_msg(f'Limiting threads to {threads}')
self.con.execute(f"SET threads={threads}")
def generate(self, unique_values, values, arrow_dict: ArrowDictionary):
self.input = []
self.expected = []
for x in range(values):
value = arrow_dict.dict[x % unique_values]
self.input.append(value)
self.expected.append((value,))
array = pa.array(
self.input,
type=pa.dictionary(pa.int64(), pa.string()),
)
self.table = pa.table([array], names=["x"])
def benchmark(self, benchmark_name) -> BenchmarkResult:
self.con.register('arrow_table', self.table)
result = BenchmarkResult(benchmark_name)
for _ in range(nruns):
duration = 0.0
start = time.time()
res = self.con.execute(
"""
select * from arrow_table
"""
).fetchall()
end = time.time()
duration = float(end - start)
assert self.expected == res
del res
padding = " " * len(str(nruns))
print_msg(f"T{padding}: {duration}s")
result.add(duration)
return result
class SelectAndCallBenchmark:
def __init__(self):
"""
SELECT statements become QueryRelations, any other statement type becomes a MaterializedRelation.
We use SELECT and CALL here because their execution plans are identical
"""
self.initialize_connection()
def initialize_connection(self):
self.con = duckdb.connect()
if not threads:
return
print_msg(f'Limiting threads to {threads}')
self.con.execute(f"SET threads={threads}")
def benchmark(self, name, query) -> List[BenchmarkResult]:
results: List[BenchmarkResult] = []
methods = {'select': 'select * from ', 'call': 'call '}
for key, value in methods.items():
for rowcount in [2048, 50000, 2500000]:
result = BenchmarkResult(f'{key}_{name}_{rowcount}')
query_string = query.format(rows=rowcount)
query_string = value + query_string
rel = self.con.sql(query_string)
print_msg(rel.type)
for _ in range(nruns):
duration = 0.0
start = time.time()
rel.fetchall()
end = time.time()
duration = float(end - start)
padding = " " * len(str(nruns))
print_msg(f"T{padding}: {duration}s")
result.add(duration)
results.append(result)
return results
class PandasDFLoadBenchmark:
def __init__(self):
self.initialize_connection()
self.generate()
def initialize_connection(self):
self.con = duckdb.connect()
if not threads:
return
print_msg(f'Limiting threads to {threads}')
self.con.execute(f"SET threads={threads}")
def generate(self):
self.con.execute("call dbgen(sf=0.1)")
new_table = "*, " + ", ".join(["l_shipdate"] * 300)
self.con.execute(f"create table wide as select {new_table} from lineitem limit 500")
self.con.execute(f"copy wide to 'wide_table.csv' (FORMAT CSV)")
def benchmark(self, benchmark_name) -> BenchmarkResult:
result = BenchmarkResult(benchmark_name)
for _ in range(nruns):
duration = 0.0
pandas_df = pd.read_csv('wide_table.csv')
start = time.time()
for _ in range(30):
res = self.con.execute("""select * from pandas_df""").df()
end = time.time()
duration = float(end - start)
del res
result.add(duration)
return result
class PandasAnalyzerBenchmark:
def __init__(self):
self.initialize_connection()
self.generate()
def initialize_connection(self):
self.con = duckdb.connect()
if not threads:
return
print_msg(f'Limiting threads to {threads}')
self.con.execute(f"SET threads={threads}")
def generate(self):
return
def benchmark(self, benchmark_name) -> BenchmarkResult:
result = BenchmarkResult(benchmark_name)
data = [None] * 9999999 + [1] # Last element is 1, others are None
# Create the DataFrame with the specified data and column type as object
pandas_df = pd.DataFrame(data, columns=['Column'], dtype=object)
for _ in range(nruns):
duration = 0.0
start = time.time()
for _ in range(30):
res = self.con.execute("""select * from pandas_df""").df()
end = time.time()
duration = float(end - start)
del res
result.add(duration)
return result
def test_arrow_dictionaries_scan():
DICT_SIZE = 26 * 1000
print_msg(f"Generating a unique dictionary of size {DICT_SIZE}")
arrow_dict = ArrowDictionary(DICT_SIZE)
DATASET_SIZE = 10000000
for unique_values in [2, 1000, DICT_SIZE]:
test = ArrowDictionaryBenchmark(unique_values, DATASET_SIZE, arrow_dict)
benchmark_name = f"arrow_dict_unique_{unique_values}_total_{DATASET_SIZE}"
result = test.benchmark(benchmark_name)
result.write()
def test_loading_pandas_df_many_times():
test = PandasDFLoadBenchmark()
benchmark_name = f"load_pandas_df_many_times"
result = test.benchmark(benchmark_name)
result.write()
def test_pandas_analyze():
test = PandasAnalyzerBenchmark()
benchmark_name = f"pandas_analyze"
result = test.benchmark(benchmark_name)
result.write()
def test_call_and_select_statements():
test = SelectAndCallBenchmark()
queries = {
'repeat_row': "repeat_row(42, 'test', True, 'this is a long string', num_rows={rows})",
}
for key, value in queries.items():
results = test.benchmark(key, value)
for res in results:
res.write()
def main():
test_tpch()
test_arrow_dictionaries_scan()
test_loading_pandas_df_many_times()
test_pandas_analyze()
test_call_and_select_statements()
close_result()
if __name__ == '__main__':
main()