提高C++性能

3

我正在尝试在C++中创建线程。我认为在for循环内创建线程并不意味着并行化。但是我想要并行化下面这段代码逻辑。

for(int i = 0; i < 100000; i++) // for each instance in the dataset
{
    for(int j = 0; j < 100000; j++) // target each other instance
    {
        if(i == j) continue;

        float distance = 0;

        for(int k = 0; k < 2000; k++)
        {
            float a = dataset->get_instance(i)->get(k)->operator float();
            float b = dataset->get_instance(j)->get(k)->operator float();
            float diff = a - b
            distance += diff * diff;
        }

        distance = distance + 10;

    }

}

上面的代码段是否有并行性的可能性?或者有没有人可以提供给我一些代码示例来理解类似线程的并行化。


首先,你需要弄清楚你有多少个硬件核心。然后,你需要以最有效的方式进行工作的测量和划分。所以,基本上就是试错直到成功。 - Incomputable
3
这段代码似乎没有任何作用。在for(j)循环中声明了distance,所以它的值在外部是未知的。 - kfsone
@kfsone:我已经更新了distance外部的使用方法,您能否提供任何指针或给我任何代码逻辑来得出结果。 - Naveen Balasubramanian
你需要先告诉我们你想要并行化什么。你正在尝试计算两点之间的最短距离,这并不一定需要并行化。 - samairtimer
1
distance仍然只在j循环内部可知,因此您在i循环末尾添加的代码是无效的,并且smallestDistance也有同样的问题。编译器可以轻松省略整个函数:https://godbolt.org/g/ywcq9x - kfsone
1个回答

4

如果所展示的函数都没有副作用,你可以简单地为每个i循环迭代运行一个线程,也可以创建N个线程并将外部i循环的迭代次数分配给每个线程,或者你可以使用std::async

struct ShortestDistance {
    float distance;
    int distClass;
};

ShortestDistance inner_loop(const Dataset* dataset, int i)
{
    ShortestDistance dist { MAX_FLT, 0 };

    for(int j = 0; j < dataset->num_instances(); j++) // target each other instance
    {
        if(i == j) continue;

        float distance = 0;

        for(int k = 0; k < dataset->num_attributes() - 1; k++) // compute the distance between the two instances
        {
            float a = dataset->get_instance(i)->get(k)->operator float();
            float b = dataset->get_instance(j)->get(k)->operator float();
            float diff = a - b
            distance += diff * diff;
        }

        distance = sqrt(distance);
        if (distance < dist.distance) {
            dist.distance = distance;
            dist.distClass = dataset->get_instance(j)->get(dataset->num_attributes() - 1)->operator int32();
        }
    }

    return dist;
}

void outer_loop(const Dataset* dataset)
{
    std::vector<std::future<ShortestDistance>> vec;
    for(int i = 0; i < dataset->num_instances(); i++) // for each instance in the dataset
    {    
        vec[i] = std::async(inner_loop, dataset, i);
    }

    DistanceResult overallResult { FLT_MAX, 0 };
    for (auto&& fut : vec)
    {
        DistanceResult threadResult = fut.get();
        if (threadResult.distance < overallResult.distance)
            overallResult = threadResult);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接