【发布时间】:2015-04-07 11:17:12
【问题描述】:
代码使用 C++11 编写。每个进程都有两个矩阵数据(稀疏)。测试数据可以从enter link description here下载
测试数据包含 2 个文件:a0(稀疏矩阵 0)和 a1(稀疏矩阵 1)。文件中的每一行都是“i j v”,表示稀疏矩阵第i行,第j列的值为v。i,j,v都是整数。
使用 c++11 unordered_map 作为稀疏矩阵的数据结构。
unordered_map<int, unordered_map<int, double> > matrix1 ;
matrix1[i][j] = v ; //means at row i column j of matrix1 is value v;
以下代码花费了大约 2 分钟。编译命令为g++ -O2 -std=c++11 ./matmult.cpp。
g++ 版本是 4.8.1,Opensuse 13.1。我的电脑信息:Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz,4G 内存。
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <thread>
using namespace std;
void load(string fn, unordered_map<int,unordered_map<int, double> > &m) {
ifstream input ;
input.open(fn);
int i, j ; double v;
while (input >> i >> j >> v) {
m[i][j] = v;
}
}
unordered_map<int,unordered_map<int, double> > m1;
unordered_map<int,unordered_map<int, double> > m2;
//vector<vector<int> > keys(BLK_SIZE);
int main() {
load("./a0",m1);
load("./a1",m2);
for (auto r1 : m1) {
for (auto r2 : m2) {
double sim = 0.0 ;
for (auto c1 : r1.second) {
auto f = r2.second.find(c1.first);
if (f != r2.second.end()) {
sim += (f->second) * (c1.second) ;
}
}
}
}
return 0;
}
上面的代码太慢了。我怎样才能让它运行得更快?我使用多线程。
新代码如下,编译命令为g++ -O2 -std=c++11 -pthread ./test.cpp。大约花了1分钟。 我希望它更快。
我怎样才能更快地完成任务?谢谢!
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <thread>
#define BLK_SIZE 8
using namespace std;
void load(string fn, unordered_map<int,unordered_map<int, double> > &m) {
ifstream input ;
input.open(fn);
int i, j ; double v;
while (input >> i >> j >> v) {
m[i][j] = v;
}
}
unordered_map<int,unordered_map<int, double> > m1;
unordered_map<int,unordered_map<int, double> > m2;
vector<vector<int> > keys(BLK_SIZE);
void thread_sim(int blk_id) {
for (auto row1_id : keys[blk_id]) {
auto r1 = m1[row1_id];
for (auto r2p : m2) {
double sim = 0.0;
for (auto col1 : r1) {
auto f = r2p.second.find(col1.first);
if (f != r2p.second.end()) {
sim += (f->second) * col1.second ;
}
}
}
}
}
int main() {
load("./a0",m1);
load("./a1",m2);
int df = BLK_SIZE - (m1.size() % BLK_SIZE);
int blk_rows = (m1.size() + df) / (BLK_SIZE - 1);
int curr_thread_id = 0;
int index = 0;
for (auto k : m1) {
keys[curr_thread_id].push_back(k.first);
index++;
if (index==blk_rows) {
index = 0;
curr_thread_id++;
}
}
cout << "ok" << endl;
std::thread t[BLK_SIZE];
for (int i = 0 ; i < BLK_SIZE ; ++i){
t[i] = std::thread(thread_sim,i);
}
for (int i = 0; i< BLK_SIZE; ++i)
t[i].join();
return 0 ;
}
【问题讨论】:
-
看来你已经回答了你自己的问题,第二个比第一个快/慢多少?滴滴你测试过吗?
-
@BajMile 第一个代码用了 2 多分钟,第二个代码用了大约 1 分钟。我希望它更快。
-
好吧,由于
auto,您在循环中复制了很多内容。让他们auto const&这样你就不会浪费所有的时间了。更快的 io 不会受到伤害。并且实际上对组件进行计时,确定哪个组件需要时间,这样您就可以专注于使该 paet 更快。哦,因为在这里发帖的人有一半忘记了,告诉编译器进行优化。 -
@Yakk 谢谢!我会试试的。
-
请参阅:stackoverflow.com/questions/15693584/… 使用不同的容器而不使用自动,如果您需要更快,我相信比 CSR 和 CSC 更快,但我需要进行测试
标签: c++ multithreading matrix