# 2023q1 Homework4 (quiz4) contributed by < `fewletter` > > [題目連結](https://hackmd.io/@sysprog/linux2023-quiz4) ## 測驗一 --- ## 測驗二 ### 程式碼運作原理 從 [Linux 核心排序實作的演進](https://hackmd.io/@sysprog/linux2023-lab0/%2F%40sysprog%2Flinux2023-lab0-e#Linux-%E6%A0%B8%E5%BF%83%E6%8E%92%E5%BA%8F%E5%AF%A6%E4%BD%9C%E7%9A%84%E6%BC%94%E9%80%B2) 中可以看到 mergesort 的觀念如何在 linked list 被利用,從 mergesort 中可以知道一個排序的方法需要的是分割 partition 與合併 merge。 > The idea of TimSort is to design a merge sort that can exploit the possible "non randomness" of the data, without having to detect it beforehand and without damaging the performances on random-looking data. This follows the ideas of adaptive sorting (see [7] for a survey on taking presortedness into account when designing and analyzing sorting algorithms) 從〈[On the Worst-Case Complexity of TimSort](https://arxiv.org/pdf/1805.08612.pdf)〉可以看到,Timsort 試圖根據資料的非隨機性(non randomness) 來改進分割資料的方式,從 mergesort 中可以看到此演演算法對待每個數字之間的關係為平等的,比如說以下面此例子作說明 ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] start[label="<f0> 1|<f1> 2|<f2> 3|<f4> 4|<f5> 6|<f6> 5|<f7> 7|<f8> 8"]; final [label="<f0> 1|<f1> 2|<f2> 3|<f4> 4|<f5> 5|<f6> 6|<f7> 7|<f8> 8"]; start:f5 -> final:f6 start:f6 -> final:f5 } ``` 如果對上例作排序,從人的視角中只需要將 5 和 6 調換即可完成排序,但是如果以 mergesort 實作,就會先將每個數字分割最後再合併,浪費了許多比較的時間。 從上述的例子可以知道分割的地方對排序的時間會有很大的影響,所以先來看看 Timsort 中的分割 (partition) 是如何進行的 ```c if (cmp(cur, next)) { while (next < last && cmp(cur, next)) { ++run_len; cur += size; next += size; } } else { while (next < last && !cmp(cur, next)) { ++run_len; cur += size; next += size; } __reverse(first, next, size); } if (next < last && run_len < MIN_RUN) { last = first + MIN_RUN * size < last ? first + MIN_RUN * size : last; __insertion_sort(first, last, size, cmp); return (last - first) / size; } return run_len; ``` 從上述程式碼中,隨著 `cmp(cur, next)` 比較次數增加 `run_len` 也跟著增加,而即使陣列沒有符合 `cmp(cur, next)` 這項條件,也會靠著 `first + MIN_RUN * size` 讓分割的位置在我們所設置的地方,以下是本測驗的陣列分割的地方,前面 960 項為符合 `cmp(cur, next)` 的數字陣列,後面則是依照 `#define MIN_RUN 16` 來分割的位置。 ``` 960 16 16 16 16 ``` 本測驗大小為 1024 的數列隨著分割的標準會分割成下面此圖 ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] length[label="<f0> 960|<f1> 16|<f2> 16|<f4> 16|<f5> 16"]; } ``` 接著再看裡面的元素確實依照著上面的的分割法進行分割 `run_length = 960` 裡面都是不需要排序的陣列,其他皆為隨機數的陣列 ```cpp run_length = 960*4 0 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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 run_length = 16*4 359 966 105 115 81 255 74 236 809 205 186 939 498 763 483 326 run_length = 16*4 124 706 84 1016 795 488 487 909 886 346 302 611 563 927 201 922 run_length = 16*4 870 306 13 951 561 88 163 346 293 349 261 791 88 745 94 212 run_length = 16*4 427 178 205 198 667 692 84 529 14 386 116 577 289 317 476 135 ``` 分割完此陣列後,接著就是要合併這些陣列,首先要問的問題是如何合併,並且此合併法有什麼優點或缺點,以下為合併的規則 ```cpp static inline bool merge_rule(run_t *stack, size_t top) { if (top < 1) return false; if (top < 2) return run_length(stack[top]) > run_length(stack[top - 1]); return run_length(stack[top]) > run_length(stack[top - 1]) || run_length(stack[top]) + run_length(stack[top - 1]) > run_length(stack[top - 2]); } ``` 首先是當 `stack` 中有兩個分割的陣列的時候,如果最上層 `stack[top]` 的長度大於第二層 `stack[top - 1]` 的長度就執行合併,第二種狀況為當最上層 `stack[top]` 的長度大於第二層 `stack[top - 1]` 的長度或是最上層 `stack[top]` 的長度加上第二層 `stack[top - 1]` 的長度大於第三層 `stack[top - 2]` 的長度執行合併,以下為示意圖 ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] length[label="<f0> 960|<f1> 16"]; result[label="不執行合併",color=white] pointto[label="<f0> top-1|<f1> top",color=white] result -> length:f0 [color=white] pointto:f1 -> length:f1 pointto:f0 -> length:f0 } ``` ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] length[label="<f0> 960|<f1> 16|<f2> 16"]; result[label="不執行合併",color=white]; pointto[label="<f0> top-2|<f1> top-1|<f2> top",color=white] result -> length:f0 [color=white] pointto:f2 -> length:f2 pointto:f1 -> length:f1 pointto:f0 -> length:f0 } ``` ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] result[label="執行合併",color=white]; length[label="<f0> 960|<f1> 16|<f2> 16|<f3> 16"]; pointto[label="<f0> top-3|<f1> top-2|<f2> top-1|<f3> top",color=white] result -> length:f0 [color=white] pointto:f3 -> length:f3 pointto:f2 -> length:f2 pointto:f1 -> length:f1 pointto:f0 -> length:f0 } ``` ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] result[label="執行合併",color=white]; length[label="<f0> 960|<f1> 16|<f2> 32"]; pointto[label="<f0> top-2|<f1> top-1|<f2> top",color=white] result -> length:f0 [color=white] pointto:f2 -> length:f2 pointto:f1 -> length:f1 pointto:f0 -> length:f0 } ``` ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] result[label="不執行合併",color=white]; length[label="<f0> 960|<f1> 48"]; pointto[label="<f0> top-1|<f1> top",color=white] result -> length:f0 [color=white] pointto:f1 -> length:f1 pointto:f0 -> length:f0 } ``` ```graphviz digraph G{ node [shape=record]; edge [arrowsize=0.8] result[label="不執行合併",color=white]; length[label="<f0> 960|<f1> 48|<f2> 16"]; pointto[label="<f0> top-2|<f1> top-1|<f2> top",color=white] result -> length:f0 [color=white] pointto:f2 -> length:f2 pointto:f1 -> length:f1 pointto:f0 -> length:f0 } ``` 接著就是進行 `stack` 中的合併,將 `top-2`,`top-1`,`top` 進行合併 ```cpp while (top > 1) { --top; if (buf) __merge(stack[top - 1].first, stack[top - 1].last, stack[top].first, stack[top].last, buf, size, cmp); else __inplace_merge(stack[top - 1].first, stack[top - 1].last, stack[top].first, stack[top].last, size, cmp); stack[top - 1].last = stack[top].last; } free(buf); ``` #### 合併策略 上述最令人好奇的是為什麼合併策略 `merge_rule` 會設計成這樣,〈[On the Worst-Case Complexity of TimSort](https://arxiv.org/pdf/1805.08612.pdf)〉提到其目的 > Tim Peter’s idea was that: “The thrust of these rules when they trigger merging is to balance the run lengths as closely as possible, while keeping a low bound on the number of runs we have to remember.” 代表此演算法想將盡量平衡每個 `run_length` 的大小,而此種合併策略 * $r_{i+2} > r_{i+1} + r_{i}$ * $r_{i+1} > r_{i}$ 會讓在`stack` 中的 `run_length` 最少以費氏數列的速度成長,而 `stack` 整體的長度 $h$ 也會有著 $log$ 一般的關係 $$ h \le 4+2log_2(\frac{n}{r}),n=\overline{r_h},r=\overline{r_1} $$ 證明: 首先先給定兩個 runs $r_i,r_j$,其中 $i \le j$ 從合併策略中可以得知 $$ \begin{aligned} 2r_i &\le r_i+r_{i+1} \le r_{i+2} \\ r_i &\le 2^{-1}r_{i+2*1} \\ r_i &\le 2^{-k}r_{i+2k} \le 2^{-k}r_{i+2k+1} \end{aligned}$$ 接著將 $i+2k$ 代換成 $j$ $$\begin{aligned} i+2k &= j \\ -k &= -\frac{-i+j}{2} \\ \Rightarrow r_i &\le 2^{(i+1-j)/2}r_j \end{aligned}$$ 假設有一 `stack` $(\overline{r_1},\overline{r_2},\overline{r_3},...\overline{r_h})$ 還未進行合併,並假設 $\overline{r_h}=n$ $$ \begin{aligned} \overline{r_3} &\le 2^{(3+1-h)/2}\overline{r_h} \\ r = \overline{r_1} \le \overline{r_3} &\le 2^{2-\frac{h}{2}} \overline{r_h} \\ log_2\frac{r}{n} &\le 2-\frac{h}{2} \\ h &\le 2(2-log_2\frac{r}{n}) \\ &= 4+2log_2\frac{n}{r} \end{aligned} $$ ### 針對 Linux 核心 lib/sort.c 程式碼,hybrid sorting 的引入和改進方案 > [lib/sort.c](https://github.com/torvalds/linux/blob/master/lib/sort.c) [lib/sort.h](https://github.com/torvalds/linux/blob/master/include/linux/sort.h) 在閱讀此份程式碼時,最令人困惑的地方是以下這段中的兩個關鍵字 `cmp_r_func_t` 和 `swap_r_func_t`,我可以理解在排序時會將自己所寫的比較函式以函式指標傳入在排序的函式中,比如說在第二個函式中 `sort()` 的 `cmp_func_t` 和 `swap_func_t`,但問題是為什麼要兩個不同的類型的函示指標? ```c void sort_r(void *base, size_t num, size_t size, cmp_r_func_t cmp_func, swap_r_func_t swap_func, const void *priv); void sort(void *base, size_t num, size_t size, cmp_func_t cmp_func, swap_func_t swap_func); ``` 然後繼續尋找下去 `swap_r_func_t` 會在哪裡出現 ```c static void do_swap(void *a, void *b, size_t size, swap_r_func_t swap_func, const void *priv) { if (swap_func == SWAP_WRAPPER) { ((const struct wrapper *)priv)->swap(a, b, (int)size); return; } if (swap_func == SWAP_WORDS_64) swap_words_64(a, b, size); else if (swap_func == SWAP_WORDS_32) swap_words_32(a, b, size); else if (swap_func == SWAP_BYTES) swap_bytes(a, b, size); else swap_func(a, b, (int)size, priv); } ``` 在這個函式中 `swap_r_func_t` 出現在引數,看著這個函式是在做兩個元素的交換,那為什麼最後一個 `swap_func()` 會需要多一個引數 `priv` ? ``` * This function does a heapsort on the given array. You may provide * a swap_func function if you need to do something more than a memory * copy (e.g. fix up pointers or auxiliary data), but the built-in swap * avoids a slow retpoline and so is significantly faster. ``` 從註解中終於找到為何要多一個 `swap_r_func()` 代表如果要讓`swap_r_func()` 不只是有複製記憶體空間並且交換這兩個空間的功能,可以自行撰寫新的 `swap_r_func()`。 接著在主程式中撰寫 `cmp()`和 `swap_r()` 程式碼測試 lib/sort.c 的效能 ```c int main() { int *sort_buf = malloc(sizeof(int) * BUF_SIZE); ... time = clock(); sort_o(sort_buf, BUF_SIZE, sizeof(int), cmp, swap_r); printf("sort: %.1f us\n", (double) (clock() - time) / CLOCKS_PER_SEC * 1e6); return 0; } static int cmp(const void *a, const void *b) { return *(int *) a - *(int *) b; } static void swap_r(void *a, void *b, int n) { do { unsigned int t = *(unsigned int *)(a + (n -= 4)); *(unsigned int *)(a + n) = *(unsigned int *)(b + n); *(unsigned int *)(b + n) = t; } while (n); } ``` 測試結果如下: ``` timsort: 84.0 us qsort: 137.0 us sort: 1085.0 us ``` 測試結果顯示 lib/sort.c 在排序上跟測驗時的 timsort 和 qsort 有著很大的差別,所以來看看 lib/sort.c 的程式碼長怎樣。 #### lib/sort.c 程式碼修改 ``` * This function does a heapsort on the given array. You may provide * a swap_func function if you need to do something more than a memory * copy (e.g. fix up pointers or auxiliary data), but the built-in swap * avoids a slow retpoline and so is significantly faster. ``` 從同樣一串註解中可以知道 lib/sort.c 採用的排序法是 heapsort。 首先修改的策略是引入 introsort 演算法,introsort 演算法同時包含 heapsort, quicksort 和 insertsort ,而從上面的測試結果可以看到,qsort 在大筆資料排序情況下,速度快於 heapsort,所以讓 quicksort 處理大筆資料,當 quicksort 將資料切分到很小的區間時,使用 heapsort 處理排序。 並且在整體資料量不多時,可以利用 insertsort 來排序,而由於 insertsort 會假設此陣列為已排序的陣列,它只會將還沒排序的元素利用插入的方法插入正確位置中,所以在有序且資料量小的陣列中 insertsort 會有較快的排序速度。 在 sort.h 中增加 `partition()`, `quicksort()` 和 `insertsort` 三個函式 ```c void insertsort(void *base, size_t num, size_t size, cmp_func_t cmp_func, swap_func_t swap_func) { for (size_t i = 1; i < num; ++i) { for (size_t j = i; j > 0 && cmp_func(base + (j-1) * size, base + j * size) > 0; --j) { swap_func(base + (j-1) * size, base + j * size, size); } } } ``` 以上是 insertsort 的程式碼,對其與 heapsort (即 lib/sort.c )做測試,測試資料為大小 300 的陣列如下 ```c for (size_t i = 0; i < BUF_SIZE; i++) { sort_buf[i] = data; newsort_buf[i] = data; } ... for (size_t i = BUF_SIZE - BUF_SIZE / 5; i < BUF_SIZE; i++) { int data = rand() % BUF_SIZE; sort_buf[i] = data; newsort_buf[i] = data; } ``` 從上面的程式碼知道此陣列為部份有序且數量不大,測試結果如下 ``` heapsort: 90.0 us insertsort: 68.0 us ``` 所以在 sort 中增加一個切換演算法的分支 ```c if (num <= 300) return insertsort(base, num, size, cmp_func, swap_func); else return heapsort(base, num, size, _CMP_WRAPPER, SWAP_WRAPPER, &w); ``` 下面則是嘗試實作出足以在排序速度快於原本 lib/sort.c 的 hybrid sort 演算法 ```c int partition(void *base, size_t num, size_t size, cmp_func_t cmp_func, swap_func_t swap_func) { void *pivot = base + num - 1; size_t i = 0; for (size_t j = 0; j < num - 1; ++j) { if (cmp_func(base + j * size, pivot) <= 0) { swap_func(base + i * size, base + j * size, size); i++; } } swap_func(base + i * size, pivot, size); return i; } ``` `partition()` 作為分割資料的函式,主要是將所有小於 pivot 的資料排到左邊,並且回傳 pivot 的位置,接著利用 `partition()` 函式實作出遞迴版本的 quicksort ,但是在測試時很明顯的不管有沒有達到 quicksort 的最差情況,遞迴版本的 quicksort 都比原本的 heapsort 還慢 ```c void quicksort(void *base, size_t num, size_t size, cmp_func_t cmp_func, swap_func_t swap_func) { if (num < 1) return; int pivot = partition(base, num, size, cmp_func, swap_func); quicksort(base, pivot, size, cmp_func, swap_func); quicksort(base + (pivot + 1) * size, num - pivot - 1, size, cmp_func, swap_func); } ``` ``` heapsort: 203.0 us quicksort: 506.0 us ``` 接著試著將遞迴版本的 quicksort 改成非遞迴版本的 quicksort ,此非遞迴版本的 quicksort 參考自 [第一周測驗二](https://hackmd.io/@sysprog/linux2023-quiz1#%E6%B8%AC%E9%A9%97-2) 中的 [Optimized Quicksort](https://alienryderflex.com/quicksort/) 首先此演算法會大量運用到 `left` 和 `right` 來記錄小於和大於 `pivot` 的值,所以先建立一個結構體來儲存這兩個值 ```c typedef struct { void *left; void *right; } _stack; ``` 接著將頭尾分別填入 `stack` 中 ```c _stack stack[32]; int top = -1; void *left = base; void *right = base + (num - 1) * size; stack[++top].left = left; stack[top].right = right; ``` :::warning TODO: 1.實作在遞迴深度超過 $2logn$ 就會切換演算法的 introsort 2.實作 lib/sort.c 風格的 timsort ::: --- ## 測驗三