c ++中汉明距离的更快形式(可能利用标准库)?

sfl*_*lee 4 c++ algorithm optimization stl

我有两个int vectors喜欢a[100],b[100].
计算汉明距离的简单方法是:

std::vector<int> a(100);
std::vector<int> b(100);

double dist = 0;    
for(int i = 0; i < 100; i++){
    if(a[i] != b[i])
        dist++;
}
dist /= a.size();
Run Code Online (Sandbox Code Playgroud)

我想问一下,有更快的方法在C++中进行此计算或如何使用STL执行相同的工作吗?

pep*_*ico 5

你要求更快的方式.这是一个令人尴尬的并行问题,因此,使用C++,您可以通过两种方式利用它:线程并行性和通过优化进行矢量化.

//The following flags allow cpu specific vectorization optimizations on *my cpu*
//clang++ -march=corei7-avx hd.cpp -o hd -Ofast -pthread -std=c++1y
//g++ -march=corei7-avx hd.cpp -o hd -Ofast -pthread -std=c++1y

#include <vector>
#include <thread>
#include <future>
#include <numeric>

template<class T, class I1, class I2>
T hamming_distance(size_t size, I1 b1, I2 b2) {
    return std::inner_product(b1, b1 + size, b2, T{},
            std::plus<T>(), std::not_equal_to<T>());
}

template<class T, class I1, class I2>
T parallel_hamming_distance(size_t threads, size_t size, I1 b1, I2 b2) {
    if(size < 1000)
       return hamming_distance<T, I1, I2>(size, b1, b2);

    if(threads > size)
        threads = size;

    const size_t whole_part = size / threads;
    const size_t remainder = size - threads * whole_part;

    std::vector<std::future<T>> bag;
    bag.reserve(threads + (remainder > 0 ? 1 : 0));

    for(size_t i = 0; i < threads; ++i)
        bag.emplace_back(std::async(std::launch::async,
                            hamming_distance<T, I1, I2>,
                            whole_part,
                            b1 + i * whole_part,
                            b2 + i * whole_part));
    if(remainder > 0)
        bag.emplace_back(std::async(std::launch::async,
                            hamming_distance<T, I1, I2>,
                            remainder,
                            b1 + threads * whole_part,
                            b2 + threads * whole_part));

    T hamming_distance = 0;
    for(auto &f : bag) hamming_distance += f.get();
    return hamming_distance;
}

#include <ratio>
#include <random>
#include <chrono>
#include <iostream>
#include <cinttypes>

int main() {
    using namespace std;
    using namespace chrono;

    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> random_0_9(0, 9);

    const auto size = 100 * mega::num;
    vector<int32_t> v1(size);
    vector<int32_t> v2(size);

    for(auto &x : v1) x = random_0_9(gen);
    for(auto &x : v2) x = random_0_9(gen);

    cout << "naive hamming distance: ";
    const auto naive_start = high_resolution_clock::now();
    cout << hamming_distance<int32_t>(v1.size(), begin(v1), begin(v2)) << endl;
    const auto naive_elapsed = high_resolution_clock::now() - naive_start;

    const auto n = thread::hardware_concurrency();

    cout << "parallel hamming distance: ";
    const auto parallel_start = high_resolution_clock::now();
    cout << parallel_hamming_distance<int32_t>(
                                                    n,
                                                    v1.size(),
                                                    begin(v1),
                                                    begin(v2)
                                              )
         << endl;
    const auto parallel_elapsed = high_resolution_clock::now() - parallel_start;

    auto count_microseconds =
        [](const high_resolution_clock::duration &elapsed) {
            return duration_cast<microseconds>(elapsed).count();
        };

    cout << "naive delay:    " << count_microseconds(naive_elapsed) << endl;
    cout << "parallel delay: " << count_microseconds(parallel_elapsed) << endl;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我没有对矢量大小进行划分

我的机器的结果(显示它对于只有2个物理核心的机器没有太大帮助...):

$ clang++ -march=corei7-avx hd.cpp -o hd -Ofast -pthread -std=c++1y -stdlib=libc++ -lcxxrt -ldl
$ ./hd
naive hamming distance: 89995190
parallel hamming distance: 89995190
naive delay:    52758
parallel delay: 47227

$ clang++ hd.cpp -o hd -O3 -pthread -std=c++1y -stdlib=libc++ -lcxxrt -ldl
$ ./hd
naive hamming distance: 90001042
parallel hamming distance: 90001042
naive delay:    53851
parallel delay: 46887

$ g++ -march=corei7-avx hd.cpp -o hd -Ofast -pthread -std=c++1y -Wl,--no-as-needed
$ ./hd
naive hamming distance: 90001825
parallel hamming distance: 90001825
naive delay:    55229
parallel delay: 49355

$ g++ hd.cpp -o hd -O3 -pthread -std=c++1y -Wl,--no-as-needed
$ ./hd
naive hamming distance: 89996171
parallel hamming distance: 89996171
naive delay:    54189
parallel delay: 44928
Run Code Online (Sandbox Code Playgroud)

另外我看到自动矢量化没有效果,可能要检查装配......

有关矢量化和编译器选项的示例,请查看我的博文.


bol*_*lov 0

据观察,即使对于增量,使用 double 也非常慢。所以你应该在(递增)中使用 int for,然后使用 double 进行除法。

作为加速,我能想到的一种测试方法是使用 SSE 指令:

伪代码:

distance = 0
SSE register e1
SSE register e2
for each 4 elements in vectors
  load 4 members from a in e1
  load 4 members from b in e2
  if e1 == e2
    continue
  else
    check each 4 members individually (using e1 and e2)
dist /= 4
Run Code Online (Sandbox Code Playgroud)

在真实的(非伪代码)程序中,可以对此进行调整,以便编译器可以使用cmov指令而不是branches.

这里的主要优点是我们从内存中读取的数据减少了 4 倍。
缺点是我们之前的每 4 次检查都会有一次额外的检查。
根据如何通过cmoves或在汇编中实现这branches一点,对于在两个向量中具有许多相邻位置且具有相同值的向量来说,这可能会更快。

我真的不知道与标准解决方案相比它的性能如何,但至少值得测试。