是什么减慢了对键对的排序速度
What is slowing down sorting the pairs on a key?
实现接受答案后的计时
将 lambda 定义从:
[] (String_pair x, String_pair y) {
return x.first < y.first;
}
自:
[] (const String_pair &x, const String_pair &y) {
return x.first < y.first;
}
将分拣时间缩短至 0.23 秒。这仍然比使用 sort
稍慢,这并不奇怪。大多数具有相同键的字符串可能在第一个字符上已经不同,并且向量中只有 1/8 的元素具有多次出现的键。
最初的问题
来自"编程珍珠"的玩具问题,在英语中查找字谜。这不是家庭作业,但您可以像对待一样对待这个问题。为了解决这个问题,我实现了教科书解决方案:
- 计算字典中每个单词的签名(单词本身,按字符排序(
- 按签名排序(所有单词都在 {签名, 单词} 对中(
- 输出具有相同签名且长度大于 1 的运行。
这当然是微不足道的,为了让它更有趣一点,我使用了ICU库(在Roland Illig的帮助下(,这样程序就不会被非ASCII字符阻塞,并且可以在芬兰语中找到字谜。
以下是完整的程序。诚然,它有点长,但要用更少的代码生成真实的测试输入和输出并不容易。
$ cat find-anagrams.cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include "unicode/ustream.h"
#include "unicode/unistr.h"
#include "unicode/schriter.h"
#include <chrono>
int main()
{
using String = icu::UnicodeString;
using String_pair = std::pair<String, String>;
using namespace std::chrono;
auto start = steady_clock::now();
// sign
std::vector<String_pair> ws;
String w;
while (std::cin >> w) {
String k{w};
auto n = k.length();
UChar *begin = k.getBuffer(n);
if (!begin) return 1;
std::stable_sort(begin, begin + n);
k.releaseBuffer(n);
ws.emplace_back(k, w);
}
auto sign_done = steady_clock::now();
// sort
std::stable_sort(ws.begin(), ws.end(),
[] (String_pair x, String_pair y) {
return x.first < y.first;
});
auto sort_done = steady_clock::now();
// squash
auto begin = ws.cbegin();
while (begin != ws.cend()) {
auto sig = begin->first;
auto run_end = std::partition_point(begin, ws.cend(),
[&sig] (String_pair x) {
return sig == x.first;
});
if ((run_end - begin) > 1) {
std::cout << begin->second;
++begin;
while (begin != run_end) {
std::cout << ' ' << begin->second;
++begin;
}
std::cout << 'n';
}
begin = run_end;
}
auto squash_done = steady_clock::now();
duration<double> time;
time = duration_cast<duration<double>>(sign_done - start);
std::cerr
<< "Read and calculate signatures:n"
<< 't' << time.count() << " secn";
time = duration_cast<duration<double>>(sort_done - sign_done);
std::cerr
<< "Sort by signatures:n"
<< 't' << time.count() << " secn";
time = duration_cast<duration<double>>(squash_done - sort_done);
std::cerr
<< "Squash and output:n"
<< 't' << time.count() << " secn";
time = duration_cast<duration<double>>(squash_done - start);
std::cerr
<< "Total:n"
<< 't' << time.count() << " secn";
return 0;
}
这是我正在使用的编译器:
$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/6.1.1/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --enable-libmpx --with-system-zlib --with-isl --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-plugin --enable-install-libiberty --with-linker-hash-style=gnu --enable-gnu-indirect-function --disable-multilib --disable-werror --enable-checking=release
Thread model: posix
gcc version 6.1.1 20160707 (GCC)
这是我编译它的方式:
g++ --std=c++0x -pedantic -Wall -O2 -std=c++14 -L/usr/lib -licui18n -licuuc -licudata -licuio find-anagrams.cpp -o cpp-find-anagrams
这就是我运行它的方式,还显示了时间:
./cpp-find-anagrams < clean-words | sort > cpp-result
Read and calculate signatures:
0.328156 sec
Stable sort by signatures:
0.512024 sec
Squash and output:
0.189494 sec
Total:
1.02967 sec
clean-words
是/usr/share/dict/words
中发现的单词,通过以下内容:
sed -n '/'"'"'s$/!p' | tr [:upper:] [:lower:] | sort --unique
换句话说,去掉带有撇号、所有大写字母和所有大写重复项的单词。
我们观察到,使用 std::stable_sort
和 lambda 进行排序花费的时间太长。相比之下,如果我对整对进行排序,大约需要一半的时间。更改,在上面的程序中:
// sort
std::stable_sort(ws.begin(), ws.end(),
[] (String_pair x, String_pair y) {
return x.first < y.first;
});
自:
// sort
std::sort(ws.begin(), ws.end());
提供以下计时:
./cpp-find-anagrams < clean-words | sort > cpp-result
Read and calculate signatures:
0.338751 sec
Sort pairs:
0.216526 sec
Squash and output:
0.168725 sec
Total:
0.724002 sec
(0.51 秒至 0.22 秒(
当然,这两种排序给出的结果相同,因为输入文件中的单词已经排序。值得注意的是,这不是sort
与stable_sort
的问题。使用stable_sort
(我知道这个输入是不必要的,但无论如何(,所以改为:
// sort
std::stable_sort(ws.begin(), ws.end());
仅对计时进行最小程度的更改:
./cpp-find-anagrams < clean-words | sort > cpp-result
Read and calculate signatures:
0.334139 sec
Stable sort by signatures:
0.264751 sec
Squash and output:
0.180663 sec
Total:
0.779552 sec
(0.22 秒至 0.26 秒(
在试图弄清楚发生了什么时,我在 SWI-Prolog 中实现了相同的算法,并注意到内置的 sort
和 keysort
谓词显示了预期的差异,即sort
需要比keysort
更长的时间。通过以下实现(再次,完整程序(:
$ cat find-anagrams.pl
:- use_module(library(apply_macros)).
:- use_module(library(pairs)).
main :-
statistics(cputime, Start),
read_words(Ws),
sign_words(Ws, Signed),
statistics(cputime, Sign_done),
keysort(Signed, Sorted),
statistics(cputime, Sort_done),
squash(Sorted, Anagrams),
maplist(anagrams_string, Anagrams, Str),
atomics_to_string(Str, "n", Output),
format(current_output, "~s~n", [Output]),
statistics(cputime, Squash_done),
format(user_error,
"Read and calculate signatures:nt~f sec~nc
Sort by signatures:nt~f sec~nc
Squash and output:nt~f sec~nc
Total:nt~f secn",
[Sign_done - Start,
Sort_done - Sign_done,
Squash_done - Sort_done,
Squash_done - Start]),
halt.
main :- halt(1).
anagrams_string(Anagrams, Str) :-
atomics_to_string(Anagrams, " ", Str).
read_words(Ws) :-
read_string(current_input, _, Input),
split_string(Input, "n", "", Ws).
sign_words(Ws, Signed) :-
maplist(string_codes, Ws, Ws_codes),
maplist(sort(0, @=<), Ws_codes, Ss_codes),
maplist(string_codes, Ss, Ss_codes),
pairs_keys_values(Signed, Ss, Ws).
squash(Sorted, Anagrams) :-
group_pairs_by_key(Sorted, Grouped),
groups_anagrams(Grouped, Anagrams).
groups_anagrams([], []).
groups_anagrams([_-Set|Rest], As) :-
length(Set, N),
( N > 1
-> As = [Set|As0]
; As = As0
),
groups_anagrams(Rest, As0).
这是我正在使用的Prolog:
$ swipl -v
SWI-Prolog version 7.3.24 for x86_64-linux
我"编译"程序(为解释器创建一个"保存状态"(:
swipl -q -O --goal=main -o swi-find-anagrams -c find-anagrams.pl
并运行它:
./swi-find-anagrams < clean-words | sort > swi-result
Read and calculate signatures:
0.928485 sec
Stable sort by signatures:
0.174832 sec
Squash and output:
0.183567 sec
Total:
1.286884 sec
当我改变时
keysort(Signed, Sorted),
跟
sort(Signed, Sorted),
我得到以下增加的排序运行时间:
./swi-find-anagrams < clean-words | sort > swi-result
Read and calculate signatures:
0.935780 sec
Sort pairs:
0.269151 sec
Squash and output:
0.187508 sec
Total:
1.392440 sec
(0.17 至 0.27 秒(
排序的最终结果是相同的,但是,正如预期的那样,仅按键排序要快得多。
问题终于来了
我错过了什么?为什么少做事成本更高?
我知道我可以使用地图来实现相同的最终结果,但了解导致这种显着减速的原因仍然很有趣。
为什么少做事成本更高?
因为您正在做更多的事情 - 在 lamba 中多次复制所有字符串需要时间。如文档 std::stable_sort中所述:
O(N·log2(N((,其中 N = std::d istance(first, last( applications of cmp.
因此,对于每次调用 cmp,您都会复制 4 个字符串。将参数类型更改为常量参考并重新测量。
运算符
当然,lambda 也做同样的事情,但string_pairs是按值传递的,额外的复制也需要一些时间。如果通过引用传递它们,则速度可能是相同的。
关于SWI-Prolog版本,当使用keysort/2
时,排序算法只比较键。但是sort/2
必须比较键,对于键相同的任何两对,还必须比较值。也有可能/可能(我没有研究过这些谓词的实现(keysort/2
直接以直接的方式对键(假设列表成员必须使用 (-)/2)
中缀运算符成对(,而sort/2
必须能够处理任意项,对于复合项,这意味着在最坏的情况下使用通用代码遍历整个项。对于对(当然,这是一个复合项(,这意味着比较(-)/2
函子,发现它是相同的,然后下降到参数并比较它们。因此,与keysort/2
相比,比较次数总是两倍。
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 为什么在读取文件大小时文件IO速度会发生变化
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 为什么 lambda 会减慢排序速度
- 为什么用std :: sort()对上升阵列(1〜100,000)排序比仅使用100,000次使用的速度要快
- 迭代合并排序,工作速度与气泡排序相同
- 大桌子的快速排序速度慢得出奇
- c++是否有一个默认的数据类,用于以合理的速度对基于索引的访问进行排序
- 在未排序的整数数组中找到最小元素的速度小于0 (n)
- 是什么减慢了对键对的排序速度