多线程实现排序

使用了3个排序方法,以及时间对比。

  1. 正常的归并排序。
  2. stl里面的sort方法
  3. 使用多线程分段使用stl里面的sort方法排序后,再使用归并排序。

线程开了总共就开了16个。

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<stack>
#include<cstring>
#include<map>
#include<bitset>
#include<unordered_map>
#include<thread>
#include<mutex>
#include<ctime>
#include<random>
using namespace std;
using ll = long long;
const int mod = 1e9 + 7;;


template<typename T,typename... args>
auto rbt(T func, args ... param) {
	auto st = clock();
	func(param...);
	return clock() - st;
}

void merge_sort(int * const beg,int *const end) {
	const int len = end - beg;
	if (len<= 1) {
		return;
	}
	merge_sort(beg, beg + len / 2);
	merge_sort(beg+len/2, end);
	int * const  tmp = new int[len];
	const int *lend = beg + len / 2;
	int *p1 = beg, *p2 = beg + len / 2;
	int *p = tmp;
	while (p1 != lend && p2 != end) {
		if (*p1 < *p2) {
			*p++ = *p1++;
		}
		else {
			*p++ = *p2++;
		}
	}
	while (p1 != lend)*p++ = *p1++;
	while (p2 != end)*p++ = *p2++;
	p = tmp;
	p1 = beg;
	while (p1 != end) *p1++ = *p++;
	

	delete []tmp;
	return;
}

void std_sort(int *a,int *b) {
	std::sort(a, b);
}
vector<thread> veth;
void  t_div(int * const beg, int *const end,int deep) {
	const int len = end - beg;
	if (len <= 1) {
		return;
	}
	if (deep == 4) {
		veth.emplace_back(thread(std_sort, beg, beg + len / 2));
		veth.emplace_back(thread(std_sort, beg + len / 2, end));
		return;
	}
	else {
		t_div(beg, beg + len / 2, deep + 1);
		t_div(beg + len / 2, end, deep + 1);
	}
	return;
}

void t_merge(int * const beg, int *const end,int deep) {
	const int len = end - beg;
	if (len <= 1|| deep==4) {
		return;
	}
	
	t_merge(beg, beg + len / 2,deep+1);
	t_merge(beg + len / 2, end,deep+1);
	
	int * const  tmp = new int[len];
	const int *lend = beg + len / 2;
	int *p1 = beg, *p2 = beg + len / 2;
	int *p = tmp;
	while (p1 != lend && p2 != end) {
		if (*p1 < *p2) {
			*p++ = *p1++;
		}
		else {
			*p++ = *p2++;
		}
	}
	while (p1 != lend)*p++ = *p1++;
	while (p2 != end)*p++ = *p2++;
	p = tmp;
	p1 = beg;
	while (p1 != end) *p1++ = *p++;


	delete[]tmp;
	return;
}


void thread_sort(int *a, int *b) {
	int len = b - a;
	if (len >= 1e4) {
		t_div(a, b, 0);
		for (auto it = veth.begin(); it != veth.end();++it) {
			it->join();
		}
		t_merge(a, b, 0);

	}
	else {
		std::sort(a, b);
	}
}
int s[10000000];
int main() {
	random_device e;
	uniform_int_distribution<int> d(0, 128);

	for (auto i = begin(s); i != end(s); ++i) {
		*i = d(e);
	}
	printf("merge_sort time:%d\n",rbt(merge_sort,begin(s), end(s)));


	for (auto i = begin(s); i != end(s); ++i) {
		*i = d(e);
	}
	printf("std_sort time:%d\n", rbt(std_sort, begin(s), end(s)) );


	for (auto i = begin(s); i != end(s); ++i) {
		*i = d(e);
	}

	printf("thread_sort time :%d\n", rbt(thread_sort, begin(s), end(s)));

	return 0;
}

posted @ 2022-05-12 15:17  _comet  阅读(254)  评论(0编辑  收藏  举报