1. 程式人生 > >linux C模擬系統負載

linux C模擬系統負載

  • linux環境下的壓力測試,通過簡單的C,模擬一個cpu io mem高的環境

使用1G系統記憶體

程式碼如下

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	pid_t pid = 0;
	int i = 0, j = 0;


	for(i=0; i<1024*10; i++)#需要改大小,修改此處
	{
		pid = fork();
		if(-1 == pid)
		{	
			while(1)
			{
				sleep(1);
			}
		}
		else if(0 == pid)
		{	
			printf("malloc\n");
			char* p = NULL;			

			for(j=0; j<1024; j++)
			{
				p = malloc(1024 * 1024 * 1024);
			}
			while(1)
			{
				sleep(1);
			}
		}
		else
		{
			printf("aaaa\n");
		}
	}
	while(1)
	{
		sleep(1);
	}
}
  • 執行:gcc +c檔案,然後執行編譯成功的c程式

IO

#include<stdio.h>
#include<stdlib.h>
int main()
{
	//int a =100000;
	int x = 6;
	FILE *fp = fopen("test.txt","w");
	FILE *fp1 = fopen("test1.txt","w");
	FILE *fp2 = fopen("test2.txt","w");
	FILE *fp3 = fopen("test3.txt","w");
	FILE *fp4 = fopen("test4.txt","w");
	while(1)
	{
		fprintf(fp,"--%d--",x);
		fprintf(fp1,"--%d--",x);
		fprintf(fp2,"--%d--",x);
		fprintf(fp3,"--%d--",x);
		fprintf(fp4,"--%d--",x);
		//system("echo 12314135 > aa.txt");
	}
	fclose(fp);
	return 0;
}

CPU

#include<stdio.h>
int main()
{
	int i=1;
	int b=2;
	int temp;
	while(1)
	{
		temp = i;
		i = b;
		b = temp;	
	}
	return 0;
}