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


你可能感兴趣的:(linux多线程写文件)