1000万数据排序

先产生1000万个随机整数,并写入文件

#include <iostream>
using namespace std;

int main()
{
	const int data_num = 10000000;

	clock_t t1 = clock();

	FILE* fp = NULL;
	fopen_s(&fp, "e:\\1000w.txt", "w");
	if (fp == NULL)
	{
		cout << "open file error" << endl;
		return -1;
	}

	srand(unsigned int(time(NULL)));

	for (int i = 0; i < data_num; i++)
	{
		int big_integer = ((rand() << 15) + rand()) % 10000000;

		fprintf(fp, "%d\n", big_integer);
	}

	clock_t t2 = clock();
	cout << "1000万整数已写入文件,用时" << (double(t2) - double(t1)) / CLOCKS_PER_SEC << "秒" << endl;

	return 0;
}

下面直接用调用算法库里的并行sort方法(简洁、高效、安全)

#include <vector>
#include <execution>
#include <iostream>
using namespace std;

int main()
{
	FILE* fp_read = NULL;
	fopen_s(&fp_read, "e:\\1000w.txt", "r");
	if (fp_read == NULL)
	{
		cout << "open read file error" << endl;
		return -1;
	}

	FILE* fp_write = NULL;
	fopen_s(&fp_write, "e:\\1000w_sort.txt", "w");
	if (fp_write == NULL)
	{
		cout << "open file error" << endl;
		return -1;
	}

	clock_t t1 = clock();

	vector<int> vec_data;
	char line[20];

	while (!feof(fp_read))
	{
		fgets(line, 20, fp_read);
		vec_data.push_back(atoi(line));
	}

	clock_t t2 = clock();
	cout << "读取1000万数据,用时" << (double(t2) - double(t1)) / CLOCKS_PER_SEC << "秒" << endl;

	sort(execution::par, vec_data.begin(), vec_data.end());

	clock_t t3 = clock();
	cout << "1000万整数排序,用时" << (double(t3) - double(t2)) / CLOCKS_PER_SEC << "秒" << endl;

	for (auto &element : vec_data)
	{
		char data[20];
		_itoa_s(element, data, 10);
		fputs(data, fp_write);		
		fputs("\n", fp_write);
	}

	clock_t t4 = clock();
	cout << "1000万已排序整数写入文件,用时" << (double(t4) - double(t3)) / CLOCKS_PER_SEC << "秒" << endl;

	cout<<"总共用时"<< (double(t4) - double(t1)) / CLOCKS_PER_SEC << "秒" << endl;

	return 0;
}

1000万数据排序,用时0.082秒,不到0.1秒,速度很不错了。如果自己手写排序,想要突破这个时间,估计得用“堆+桶+多线程”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值