linux多线程写文件和单线程写文件的速度对比

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <time.h>

void saveFile(char* fileName);
char* int2stirng(int number);



int main()
{
	int i = 0;
	char* num = {"123"};
	char* ex = {".txt"};
	char* fileName;
	clock_t t_0 = clock();
	printf("文件正在写入中……\n");
	for(i = 0; i < 150; i++)
	{
		num = int2stirng(i);
		fileName = strcat(num, ex);
		saveFile(fileName);
	}
	//saveFile(hello);

	clock_t t_1 = clock();
	printf("文件写入完毕,共用时%d\n",(unsigned int)(t_1 - t_0));
	system("pause");
	return 0;
}

// 保存文件功能的具体实现函数
void saveFile(char* fileName)
{
	FILE* data;
	time_t t;
	int i = 0;
	int number = 0;

	srand((unsigned int)time(&t));

	if((data = fopen(fileName, "a")) == NULL)
	{
		printf("文件打开失败");
		system("pause");
		exit(-1);
	}
	else
	{
		for(i = 0; i < 1150000;i ++)
		{
			number = rand();
			fprintf(data, "this is the save number pragma , it is use for write char the rand number\n");
		}
	}
	fclose(data);
}

char* int2stirng(int number)
{
	char* ch = (char*)malloc(10);
	sprintf(ch,"%d",number);
	return ch;
}

以上为线程执行的代码,写入150个10M的文件共用时间:10900000ms

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <time.h>

void saveFile(char* fileName);
char* int2stirng(int number);



int main()
{
	int i = 0;
	char* num = {"123"};
	char* ex = {".txt"};
	char* fileName;
	clock_t t_0 = clock();
	printf("文件正在写入中……\n");

        #pragma omp parallel for
	for(i = 0; i < 100; i++)
	{
		num = int2stirng(i);
		fileName = strcat(num, ex);
		saveFile(fileName);
	}
	//saveFile(hello);

	clock_t t_1 = clock();
	printf("文件写入完毕,共用时%d\n",(unsigned int)(t_1 - t_0));
	system("pause");
	return 0;
}

// 保存文件功能的具体实现函数
void saveFile(char* fileName)
{
	FILE* data;
	time_t t;
	int i = 0;
	int number = 0;

	srand((unsigned int)time(&t));

	if((data = fopen(fileName, "a")) == NULL)
	{
		printf("文件打开失败");
		system("pause");
		exit(-1);
	}
	else
	{
                #pragma omp parallel for
		for(i = 0; i < 1150000;i ++)
		{
			number = rand();
			fprintf(data, "this is the save number pragma , it is use for write char the rand number\n");
		}
	}
	fclose(data);
}

char* int2stirng(int number)
{
	char* ch = (char*)malloc(10);
	sprintf(ch,"%d",number);
	return ch;
}
以下是利用omp进行写文件,写150个文件共用时间52340000ms


转载于:https://my.oschina.net/shuinian/blog/129630

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值