【问题标题】:Increasing Performance in C++提高 C++ 的性能
【发布时间】:2016-09-12 05:46:47
【问题描述】:

我正在尝试用 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;

    }

}

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

【问题讨论】:

  • 嗯,首先你需要知道你有多少个硬件核心。然后你需要以最有效的方式衡量和划分工作。所以,基本上尝试和失败直到成功。
  • 这段代码似乎没有做任何事情。 distancefor(j) 循环内声明,因此外部的值未知。
  • @kfsone:我已经更新了距离外的用法,请您提供任何指针或给我任何代码逻辑作为结果。
  • 你需要先让我们知道你想要并行化什么。您正在尝试计算两点之间的最短距离,这不需要并行化。
  • distance 仍然只在j 循环内已知,因此您在i 循环末尾添加的代码无效,smallestDistance 也有同样的问题。编译器可以很容易地省略整个函数:godbolt.org/g/ywcq9x

标签: c++ multithreading c++11 parallel-processing c++14


【解决方案1】:

如果显示的函数都没有副作用,您可以简单地在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);
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-07
    • 1970-01-01
    • 2016-11-09
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2018-12-10
    • 2021-07-19
    相关资源
    最近更新 更多