From patchwork Thu Sep 14 18:37:02 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Adhemerval Zanella Netto X-Patchwork-Id: 722586 Delivered-To: patch@linaro.org Received: by 2002:adf:f0d1:0:b0:31d:da82:a3b4 with SMTP id x17csp551886wro; Thu, 14 Sep 2023 11:37:50 -0700 (PDT) X-Google-Smtp-Source: AGHT+IFlKeEIP8PHbnTJVp6g4ptsQP93JcO03ryq+32TbAORtVh6FQJGKkBhVUvRkmiV2O+RJ9bm X-Received: by 2002:a2e:94ca:0:b0:2bd:e08:1352 with SMTP id r10-20020a2e94ca000000b002bd0e081352mr4868115ljh.5.1694716670387; Thu, 14 Sep 2023 11:37:50 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1694716670; cv=none; d=google.com; s=arc-20160816; b=a7H8bvDGnzO1J6cvCnqsSJGdhfxIJbnq8iSlAQTwrCcMSlVIeztCOppnqOOWOENt6f +kbj33y5llPoWyGTttvoNtgmBEpwQzvK1xwbBB9yK2/GbGwnDxrN/lk3bsvnLqUWKiwz CAHmsamMzf8OGGzxI/mZFaeCkDbDAaXVYILgKr9231gS9CNWw1zNUDOESAQbr8W7eNhn 7MZQXYrNyijBON2huAQ6RBP4AH5+3ZpydlECthZgOWJ5CnoixP3ZN2FzuB8WbSftMPqy llA5S3mhe4UHrf3Ei1AcHQXki7A5roWItRAz2/CZ008h/4nNOXBa2SLnLW3jFXAKsMwF aFlA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=errors-to:list-subscribe:list-help:list-post:list-archive :list-unsubscribe:list-id:precedence:content-transfer-encoding :mime-version:references:in-reply-to:message-id:date:subject:to:from :dkim-signature:dmarc-filter:delivered-to; bh=LVH9FPyqXhMnof20qz68Oz9ngaGXWyE1ZxEz6o7y/lg=; fh=ubzLPtaquqORyAJ/TX35zypB35/iXKzZJOEWlgP8mu4=; b=Z02U1IpctttiytIoHee6MEhFDl7Kw5BG0u/eNogaIMPcpnQXaajtkElQIwNYPxt0Hz KKrMr+g2Xu66PEmTxUobCUPDB4gVNeu+6ghyTCSgeHwitBWlzHNcoK9SPGBQHwuCdqo0 2A2S1t52iF1hG6d57SXPTPJ7PMmPPw/jq9UNIzmDYIZj+NXc+5Nzufv2Y9X/jcDUavi6 +wBctXDInmPmKG7ktLbZRTaX0eaeUzNPDJjhl7LAyq8Qyg80tCkBQRRc/z6HCiuQ+Xk4 IJ0d/W6Yjc18VRgldiHz0SQET3r1xP9B7aG3+UND8JT8ajhx64f8vIG5Yv1K/ot1MMt4 FhUA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@linaro.org header.s=google header.b=Lt4OziuY; spf=pass (google.com: domain of libc-alpha-bounces+patch=linaro.org@sourceware.org designates 8.43.85.97 as permitted sender) smtp.mailfrom="libc-alpha-bounces+patch=linaro.org@sourceware.org"; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=linaro.org Return-Path: Received: from server2.sourceware.org (ip-8-43-85-97.sourceware.org. [8.43.85.97]) by mx.google.com with ESMTPS id si16-20020a170906ced000b0099332c48e49si1891157ejb.133.2023.09.14.11.37.50 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 14 Sep 2023 11:37:50 -0700 (PDT) Received-SPF: pass (google.com: domain of libc-alpha-bounces+patch=linaro.org@sourceware.org designates 8.43.85.97 as permitted sender) client-ip=8.43.85.97; Authentication-Results: mx.google.com; dkim=pass header.i=@linaro.org header.s=google header.b=Lt4OziuY; spf=pass (google.com: domain of libc-alpha-bounces+patch=linaro.org@sourceware.org designates 8.43.85.97 as permitted sender) smtp.mailfrom="libc-alpha-bounces+patch=linaro.org@sourceware.org"; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=linaro.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 356213854833 for ; Thu, 14 Sep 2023 18:37:48 +0000 (GMT) X-Original-To: libc-alpha@sourceware.org Delivered-To: libc-alpha@sourceware.org Received: from mail-oi1-x22a.google.com (mail-oi1-x22a.google.com [IPv6:2607:f8b0:4864:20::22a]) by sourceware.org (Postfix) with ESMTPS id 54F043857704 for ; Thu, 14 Sep 2023 18:37:22 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 54F043857704 Authentication-Results: sourceware.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=linaro.org Received: by mail-oi1-x22a.google.com with SMTP id 5614622812f47-3aca0934e74so711307b6e.0 for ; Thu, 14 Sep 2023 11:37:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1694716641; x=1695321441; darn=sourceware.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to; bh=LVH9FPyqXhMnof20qz68Oz9ngaGXWyE1ZxEz6o7y/lg=; b=Lt4OziuYSifpujOmJQ7jzOMcnnVoPcGuqIyYKm4/oWOHHKYqXxfM6iLwvLnEu4tiHQ AIrWfD+HtGmRAn8doxd7PBv2T63Aw+obYdr/HpFRbvAWZQFsqrMLXkokIo/YVOey4D2P qSPC2lx6mnt67UybyrIXLvOV4ZxlnIlmnpNQiDMrO2MQ4JToo0W7B8ItOnu0K6pHhNlb kmM+8WtYzmL7XxQ6UmFhhtdUSwzH7IFWc07FDFhRZM3NrUXs/tgVJ0kmS1DrGPMNISx7 WO5splVsQezbirWQbaEIt9l5BDu8SUiwvnOhphoORY2yr68D9RFYCptwbWZfYwBvhvqH g2QQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1694716641; x=1695321441; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=LVH9FPyqXhMnof20qz68Oz9ngaGXWyE1ZxEz6o7y/lg=; b=eNgq7H338qfVLZLFgDrlaCoMYSrAxwukcNQuGOwFNs838yRt/1S+sEfj/0R/febfz/ JF3Alw2IXKrhUrbpbkcNGm8Io6v5e8w0Rk7aSH8+yrAxASjdzwXwhJbFoURErMqCy1Tt q/Fcm70pWX88b3wD8dJeNryS5HKpucdZdqv/lgcvUY3KkrV9o5OLLHPod6RPoZ2nmujJ bu2Za329Tc+uFI+qBive9hu4yTAo13yodSy4QjgEwPvwXcB6prOwDrIrKbwKD0y7bFjg SOdIbC4OEp8NAV+RFrlh9H2Eq8lWaLP25CUTHp+kNk0xvuDfm/HD/qE816Y+wRyFXDXs VKcw== X-Gm-Message-State: AOJu0Yx7WyZwYII3yL43PDvweNYyaH9qZMoWU7WHquOtC5GFA35rqo7q 9pWvBj44v5UL/aCDtk5cSAyutxuMrYNjpMi15wSbfw== X-Received: by 2002:a05:6870:32d3:b0:1c0:fe16:90f8 with SMTP id r19-20020a05687032d300b001c0fe1690f8mr6837368oac.57.1694716641049; Thu, 14 Sep 2023 11:37:21 -0700 (PDT) Received: from mandiga.. ([2804:1b3:a7c0:91cb:5173:d70:d8d:4d2c]) by smtp.gmail.com with ESMTPSA id cc6-20020a056871e18600b001b3d67934e9sm1056930oac.26.2023.09.14.11.37.19 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 14 Sep 2023 11:37:20 -0700 (PDT) From: Adhemerval Zanella To: libc-alpha@sourceware.org, Noah Goldstein , Paul Eggert , Florian Weimer Subject: [PATCH v7 5/7] stdlib: Implement introsort for qsort (BZ 19305) Date: Thu, 14 Sep 2023 15:37:02 -0300 Message-Id: <20230914183704.1386534-6-adhemerval.zanella@linaro.org> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230914183704.1386534-1-adhemerval.zanella@linaro.org> References: <20230914183704.1386534-1-adhemerval.zanella@linaro.org> MIME-Version: 1.0 X-Spam-Status: No, score=-12.5 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, RCVD_IN_DNSWL_NONE, SPF_HELO_NONE, SPF_PASS, TXREP autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: libc-alpha@sourceware.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Libc-alpha mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libc-alpha-bounces+patch=linaro.org@sourceware.org This patch makes the quicksort implementation to acts as introsort, to avoid worse-case performance (and thus making it O(nlog n)). It switch to heapsort when the depth level reaches 2*log2(total elements). The heapsort is a textbook implementation. Checked on x86_64-linux-gnu. --- stdlib/qsort.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 80 insertions(+), 7 deletions(-) diff --git a/stdlib/qsort.c b/stdlib/qsort.c index 4082f5f9c1..e160932657 100644 --- a/stdlib/qsort.c +++ b/stdlib/qsort.c @@ -97,6 +97,7 @@ typedef struct { char *lo; char *hi; + size_t depth; } stack_node; /* The stack needs log (total_elements) entries (we could even subtract @@ -106,22 +107,83 @@ typedef struct enum { STACK_SIZE = CHAR_BIT * sizeof (size_t) }; static inline stack_node * -push (stack_node *top, char *lo, char *hi) +push (stack_node *top, char *lo, char *hi, size_t depth) { top->lo = lo; top->hi = hi; + top->depth = depth; return ++top; } static inline stack_node * -pop (stack_node *top, char **lo, char **hi) +pop (stack_node *top, char **lo, char **hi, size_t *depth) { --top; *lo = top->lo; *hi = top->hi; + *depth = top->depth; return top; } +/* A fast, small, non-recursive O(nlog n) heapsort, adapted from Linux + lib/sort.c. Used on introsort implementation as a fallback routine with + worst-case performance of O(nlog n) and worst-case space complexity of + O(1). */ + +static inline void +siftdown (void *base, size_t size, size_t k, size_t n, + enum swap_type_t swap_type, __compar_d_fn_t cmp, void *arg) +{ + while (k <= n / 2) + { + size_t j = 2 * k; + if (j < n && cmp (base + (j * size), base + ((j + 1) * size), arg) < 0) + j++; + + if (cmp (base + (k * size), base + (j * size), arg) >= 0) + break; + + do_swap (base + (size * j), base + (k * size), size, swap_type); + k = j; + } +} + +static inline void +heapify (void *base, size_t size, size_t n, enum swap_type_t swap_type, + __compar_d_fn_t cmp, void *arg) +{ + size_t k = n / 2; + while (1) + { + siftdown (base, size, k, n, swap_type, cmp, arg); + if (k-- == 0) + break; + } +} + +static void +heapsort_r (void *base, void *end, size_t size, enum swap_type_t swap_type, + __compar_d_fn_t cmp, void *arg) +{ + const size_t count = ((uintptr_t) end - (uintptr_t) base) / size; + + if (count < 2) + return; + + size_t n = count - 1; + + /* Build the binary heap, largest value at the base[0]. */ + heapify (base, size, n, swap_type, cmp, arg); + + /* On each iteration base[0:n] is the binary heap, while base[n:count] + is sorted. */ + while (n > 0) + { + do_swap (base, base + (n * size), size, swap_type); + n--; + siftdown (base, size, 0, n, swap_type, cmp, arg); + } +} static inline void insertion_sort_qsort_partitions (void *const pbase, size_t total_elems, @@ -207,7 +269,7 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, const size_t max_thresh = MAX_THRESH * size; - if (total_elems == 0) + if (total_elems <= 1) /* Avoid lossage with unsigned arithmetic below. */ return; @@ -219,15 +281,26 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, else swap_type = SWAP_BYTES; + /* Maximum depth before quicksort switches to heapsort. */ + size_t depth = 2 * (sizeof (size_t) * CHAR_BIT - 1 + - __builtin_clzl (total_elems)); + if (total_elems > MAX_THRESH) { char *lo = base_ptr; char *hi = &lo[size * (total_elems - 1)]; stack_node stack[STACK_SIZE]; - stack_node *top = stack + 1; + stack_node *top = push (stack, NULL, NULL, depth); while (stack < top) { + if (depth == 0) + { + heapsort_r (lo, hi, size, swap_type, cmp, arg); + top = pop (top, &lo, &hi, &depth); + continue; + } + char *left_ptr; char *right_ptr; @@ -291,7 +364,7 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, { if ((size_t) (hi - left_ptr) <= max_thresh) /* Ignore both small partitions. */ - top = pop (top, &lo, &hi); + top = pop (top, &lo, &hi, &depth); else /* Ignore small left partition. */ lo = left_ptr; @@ -302,13 +375,13 @@ _quicksort (void *const pbase, size_t total_elems, size_t size, else if ((right_ptr - lo) > (hi - left_ptr)) { /* Push larger left partition indices. */ - top = push (top, lo, right_ptr); + top = push (top, lo, right_ptr, depth - 1); lo = left_ptr; } else { /* Push larger right partition indices. */ - top = push (top, left_ptr, hi); + top = push (top, left_ptr, hi, depth - 1); hi = right_ptr; } }