先产生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秒,速度很不错了。如果自己手写排序,想要突破这个时间,估计得用“堆+桶+多线程”。