海量不重复数据的生成

4 篇文章 0 订阅




    前几天看到了一个项目需求,自己尝试写了下3亿行数据大概需要20分钟的时间,普通硬盘应该要慢些,内存映射或者内存盘应该会更快一点,懒得验证了,放出代码供学习下,算法是以前偶然看到得很巧的的算法,二次获取随机数是为了数据更随机(待验证,我觉得不需要)


#include "stdafx.h"
#include <chrono>
#include <iostream>
#include <memory>
#include <random>

#include <strsafe.h>

using namespace std;


int GetRandomNum(int min, int max,int seed)
{

	//srand((unsigned)time(NULL)); //生成种子
	srand(seed);
	return( rand() % (max - min) + min);
}

int main()
{

	//int nSericalLenth = 10;

	chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
	int64_t nArrayLength = 300000000;
	FILE* pFile = 0;

	TCHAR szBuffer[128];

	memset(szBuffer, 0, sizeof(szBuffer));

	try
	{

		std::random_device rd;
		std::uniform_int_distribution<int> dist(0, 9999999);
		//std::cout << dist(rd) << std::endl;

		_tfopen_s(&pFile, _T("D:\\num.txt"), _T("wt"));

		if (pFile != nullptr)
		{
			unique_ptr<int[]> needArray(new int[nArrayLength]);

			for (int idx = 0; idx < nArrayLength; idx++)
			{
				needArray[idx] = idx+283823423;
			}

			int end = nArrayLength - 1;

			for (int i = 0; i < nArrayLength; i++)
			{
				int num = GetRandomNum(0, end + 1, dist(rd));

				StringCbPrintf(szBuffer, sizeof(szBuffer), _T("%010d\n"), needArray[num]);
				fwrite(szBuffer, 1, _tcslen(szBuffer), pFile);
				//output[i] = needArray[num];
				needArray[num] = needArray[end];
				end--;
			}

			fclose(pFile);
		}

	}
	catch (...)
	{
		
	}


	chrono::steady_clock::time_point t2 = chrono::steady_clock::now();

	cout << chrono::duration_cast<std::chrono::seconds>(t2 - t1).count() << endl;

    return 0;
}









  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值