Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions cpp/src/arrow/c/bridge.cc
Original file line number Diff line number Diff line change
Expand Up @@ -689,19 +689,24 @@ struct ArrayExporter {

} // namespace

Status ExportArray(const Array& array, struct ArrowArray* out,
Status ExportArray(std::shared_ptr<ArrayData> array, struct ArrowArray* out,
struct ArrowSchema* out_schema) {
SchemaExportGuard guard(out_schema);
if (out_schema != nullptr) {
RETURN_NOT_OK(ExportType(*array.type(), out_schema));
RETURN_NOT_OK(ExportType(*array->type, out_schema));
}
ArrayExporter exporter;
RETURN_NOT_OK(exporter.Export(array.data()));
RETURN_NOT_OK(exporter.Export(std::move(array)));
exporter.Finish(out);
guard.Detach();
return Status::OK();
}

Status ExportArray(const Array& array, struct ArrowArray* out,
struct ArrowSchema* out_schema) {
return ExportArray(array.data(), out, out_schema);
}

Status ExportRecordBatch(const RecordBatch& batch, struct ArrowArray* out,
struct ArrowSchema* out_schema) {
// XXX perhaps bypass ToStructArray() for speed?
Expand Down
7 changes: 7 additions & 0 deletions cpp/src/arrow/c/bridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ ARROW_EXPORT
Status ExportArray(const Array& array, struct ArrowArray* out,
struct ArrowSchema* out_schema = NULLPTR);

/// \brief Export C++ ArrayData using the C data interface format.
///
/// Same as the Array overload, without needing an Array wrapper.
ARROW_EXPORT
Status ExportArray(std::shared_ptr<ArrayData> array, struct ArrowArray* out,
struct ArrowSchema* out_schema = NULLPTR);

/// \brief Export C++ RecordBatch using the C data interface format.
///
/// The record batch is exported as if it were a struct array.
Expand Down
1 change: 1 addition & 0 deletions python/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ set(PYARROW_CPP_SRCS
${PYARROW_CPP_SOURCE_DIR}/inference.cc
${PYARROW_CPP_SOURCE_DIR}/io.cc
${PYARROW_CPP_SOURCE_DIR}/ipc.cc
${PYARROW_CPP_SOURCE_DIR}/numba.cc
${PYARROW_CPP_SOURCE_DIR}/numpy_convert.cc
${PYARROW_CPP_SOURCE_DIR}/numpy_init.cc
${PYARROW_CPP_SOURCE_DIR}/numpy_to_arrow.cc
Expand Down
209 changes: 209 additions & 0 deletions python/benchmarks/numba.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""Compiled (Numba) code reading and building Arrow arrays, per type."""

from typing import ClassVar

import pyarrow as pa
from benchmarks.numba_common import N, dense_values, numba_module, require, values

READ_TYPES = {
"int8": pa.int8(), "int16": pa.int16(),
"int32": pa.int32(), "int64": pa.int64(),
"uint8": pa.uint8(), "uint16": pa.uint16(),
"uint32": pa.uint32(), "uint64": pa.uint64(),
"float32": pa.float32(), "float64": pa.float64(),
"date32": pa.date32(), "date64": pa.date64(),
"time32_s": pa.time32("s"), "time64_us": pa.time64("us"),
"timestamp_us": pa.timestamp("us"), "duration_s": pa.duration("s"),
"bool": pa.bool_(),
"decimal128": pa.decimal128(20, 2),
"string": pa.string(), "large_string": pa.large_string(),
"binary": pa.binary(), "large_binary": pa.large_binary(),
"fixed_size_binary": pa.binary(8),
}

BUILD_TYPES = {
"int8": "Int8Builder", "int16": "Int16Builder",
"int32": "Int32Builder", "int64": "Int64Builder",
"uint8": "UInt8Builder", "uint16": "UInt16Builder",
"uint32": "UInt32Builder", "uint64": "UInt64Builder",
"float32": "Float32Builder", "float64": "Float64Builder",
"bool": "BoolBuilder",
"string": "StringBuilder", "large_string": "LargeStringBuilder",
"binary": "BinaryBuilder", "large_binary": "LargeBinaryBuilder",
}

BYTES_BUILDERS = ("string", "binary", "large_string", "large_binary")


class NumbaRead:
"""Read one array of every supported type, element by element."""

param_names: ClassVar[list[str]] = ["arrow_type"]
params: ClassVar[list[list[str]]] = [sorted(READ_TYPES)]

def setup(self, arrow_type):
nb = numba_module()
from pyarrow.numba import decimal_to_float, string_len
from pyarrow.numba._utils import _is_var_width

self.array = pa.array(values(arrow_type), type=READ_TYPES[arrow_type])

if arrow_type == "bool":
@nb.njit
def scan(a):
n = 0
for i in range(len(a)):
if a[i] is not None and a[i]:
n += 1
return n
elif pa.types.is_decimal(READ_TYPES[arrow_type]):
@nb.njit
def scan(a):
total = 0.0
for i in range(len(a)):
if a[i] is not None:
total += decimal_to_float(a[i], 2)
return total
elif _is_var_width(READ_TYPES[arrow_type]):
@nb.njit
def scan(a):
n = 0
for i in range(len(a)):
v = a[i]
if v.valid:
n += string_len(v)
return n
else:
@nb.njit
def scan(a):
total = 0
nulls = 0
for i in range(len(a)):
if a[i] is None:
nulls += 1
else:
total += a[i]
return total, nulls

self.func = scan
self.func(self.array) # compile outside the measured region

def time_read(self, arrow_type):
self.func(self.array)


class NumbaBuild:
"""Append one million values of every builder type, then finish."""

param_names: ClassVar[list[str]] = ["arrow_type"]
params: ClassVar[list[list[str]]] = [sorted(BUILD_TYPES)]

def setup(self, arrow_type):
nb = numba_module()
import pyarrow.numba as apn

builder_cls = getattr(apn, BUILD_TYPES[arrow_type])

if arrow_type in BYTES_BUILDERS:
@nb.njit
def build(n):
b = builder_cls()
b.reserve(n)
for i in range(n):
if i % 3:
b.append(b"abcdefgh")
else:
b.append(None)
return b.finish()
elif arrow_type == "bool":
@nb.njit
def build(n):
b = builder_cls()
b.reserve(n)
for i in range(n):
if i % 3:
b.append(i % 2 == 0)
else:
b.append(None)
return b.finish()
else:
# one append per element, no arithmetic in the loop: the append
# (reserve check, cast, store) is what is being measured
@nb.njit
def build(n):
b = builder_cls()
b.reserve(n)
for i in range(n):
if i % 3:
b.append(i)
else:
b.append(None)
return b.finish()

self.func = build
self.func(16) # compile outside the measured region

def time_build(self, arrow_type):
self.func(N)


class NumbaBuildBulk:
"""Append one million values of every fixed-width type in one batch.

Bytes types are absent because a bulk append needs one length per
element, not a flat array.
"""

param_names: ClassVar[list[str]] = ["arrow_type"]
params: ClassVar[list[list[str]]] = [
sorted(t for t in BUILD_TYPES if t not in BYTES_BUILDERS)
]

def setup(self, arrow_type):
require("bulk_builders")
nb = numba_module()
import pyarrow.numba as apn

builder_cls = getattr(apn, BUILD_TYPES[arrow_type])
self.values = dense_values()

if arrow_type == "bool":
@nb.njit
def build(values):
b = builder_cls()
b.append_many(values)
return b.finish()

self.func = build
self.arg = self.values % 3 == 0
else:
@nb.njit
def build(values):
b = builder_cls()
b.append_many(values)
return b.finish()

self.func = build
self.arg = self.values.astype(arrow_type)

self.func(self.arg[:16]) # compile outside the measured region

def time_build(self, arrow_type):
self.func(self.arg)
105 changes: 105 additions & 0 deletions python/benchmarks/numba_common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""Shared sizes and data for the Numba benchmarks."""

from decimal import Decimal

import numpy as np

import pyarrow as pa

N = 1 << 20

# The optional features this revision implements; ``require`` skips the
# benchmarks of the others.
FEATURES = frozenset()


class Unavailable(NotImplementedError):
"""A benchmark skipped on purpose (asv skips a setup raising it)."""


def require(feature):
if feature is not None and feature not in FEATURES:
raise Unavailable(f"{feature} is not in this revision")


def numba_module():
"""``numba``, after importing ``pyarrow.numba`` to register its types."""
try:
import numba
except ImportError:
raise Unavailable("numba is not installed")
import pyarrow.numba # noqa: F401 (registers the array and builder types)
return numba


def nullable_ints(n=N):
"""Every third element null."""
data = np.arange(n, dtype=np.int64)
return pa.array(np.where(np.arange(n) % 3, data, 0),
mask=np.arange(n) % 3 == 0)


def dense_ints(n=N):
"""No null bitmap at all."""
return pa.array(np.arange(n, dtype=np.int64))


def dense_values(n=N):
"""A raw ``int64`` array: what a bulk append consumes."""
return np.arange(n, dtype=np.int64)


def null_mask(n=N):
"""One ``bool_`` per element: False marks a null, every third one."""
return (np.arange(n) % 3) != 0


def strings(n=N):
return pa.array([b"abcdefgh" if i % 3 else None for i in range(n)],
type=pa.string())


def chunked_strings(n=N):
source = strings(n)
return pa.chunked_array([source[: n // 2], source[n // 2:]])


def chunked_ints(n=N):
data = np.arange(n, dtype=np.int64)
return pa.chunked_array([pa.array(data[: n // 2]), pa.array(data[n // 2:])],
type=pa.int64())


def batch(n=N):
return pa.record_batch({"x": pa.array(np.arange(n, dtype=np.int64))})


def values(arrow_type, n=N):
"""One million values of *arrow_type*, null every third."""
if arrow_type == "bool":
return [(i % 2 == 0) if i % 3 else None for i in range(n)]
if arrow_type == "decimal128":
return [Decimal(i % 10000) / 100 if i % 3 else None for i in range(n)]
if arrow_type == "fixed_size_binary":
return [b"abcdefgh" if i % 3 else None for i in range(n)]
if arrow_type in ("string", "large_string", "binary", "large_binary"):
return [b"abcdefgh"[: (i % 8) + 1] if i % 3 else None
for i in range(n)]
return [i % 100 if i % 3 else None for i in range(n)]
Loading
Loading