zoukankan      html  css  js  c++  java
  • mmap,malloc分配随机内存

    随机数1G

    #cat malloc_rand_1g.c
    #include <stdio.h>  /* printf, scanf, NULL */
    #include <stdlib.h>  /* malloc, free, rand, system */
    #include <unistd.h>
    #include <memory.h>
    
    int main ()
    {
        int size;
    	int	n;
        char * buffer;
    	size=1024*1024*1024; //1G
        printf ("输入字符串的长度:%d bytes
    ",size);
    	//scanf ("%d", &i);
    
        buffer = (char*)malloc(sizeof(char) * size);  // 字符串最后包含 
        if(buffer==NULL) exit(1);  // 判断是否分配成功
    
    	memset(buffer,'a',sizeof(char) * size);
    	printf("total bytes:%d bytes 
    ",sizeof(char) * size);
        // 随机生成字符串
        for(n=0; n<size; n++){
            buffer[n] = rand()%26+'a';
    //		printf("%c",buffer[n]);
    	}
    	printf("
    ");
    
        buffer[size+1]='';
      //  printf ("随机生成的字符串为:%s
    ",buffer);
    
    	printf("wait about 1800s....
    ");
    	sleep(1800);
        free(buffer);  // 释放内存空间
    	printf("clean up....
    ");
        return 0;
    }
    
    

    memset(a)

    #cat  malloc_a_1g.c
    #include <stdio.h>  /* printf, scanf, NULL */
    #include <stdlib.h>  /* malloc, free, rand, system */
    #include <unistd.h>
    #include <memory.h>
    
    int main ()
    {
        int size;
    	int	n;
        char * buffer;
    	size=1024*1024*1024; //1G
        printf ("输入字符串的长度:%d bytes
    ",size);
    	//scanf ("%d", &i);
    
        buffer = (char*)malloc(sizeof(char) * size);  // 字符串最后包含 
        if(buffer==NULL) exit(1);  // 判断是否分配成功
    
    	memset(buffer,'a',sizeof(char) * size);
    	printf("total bytes:%d bytes 
    ",sizeof(char) * size);
        // 随机生成字符串
        for(n=0; n<size; n++){
            buffer[n] = 'a';
    //		printf("%c",buffer[n]);
    	}
    	printf("
    ");
    
        buffer[size+1]='';
      //  printf ("随机生成的字符串为:%s
    ",buffer);
    
    	printf("wait about 1800s....
    ");
    	sleep(1800);
        free(buffer);  // 释放内存空间
    	printf("clean up....
    ");
        return 0;
    }
    
    

    mmap

    #cat mmap_1g.c
    #include<stdio.h>
    #include<sys/mman.h>
    #include<unistd.h>
    #include<stdlib.h>
    #include<string.h>
    #define SIZE  1024*1024*1024
    #define GB 1
    int main(int argc,char* argv[]) {
        char *p;
    	int i=1;
    	for (i=1;i<=GB;i++) {
    		if ((p = (char *)mmap(NULL,SIZE, PROT_READ |
    					PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)) == (void *)-1) {
    			perror("mmap");
    		 }
    		memset(p,'c',SIZE);
    		printf("Get %d GB...
    ",i);
    	}
    	sleep(3000);
    	return 0;
    }
    
    
  • 相关阅读:
    tensorflow学习3---mnist
    tensorflow学习2-线性拟合和神经网路拟合
    关于泛型数据结构中OrderBy的使用
    敏捷开发之观察者模式
    敏捷开发之设计文档
    C#算法实现获取树的高度
    武林高手?敏捷开发,唯velocity取胜
    C#接口多继承方法重名问题
    .Net平台技术栈?不止于此
    浅谈C#中Tuple和Func的使用
  • 原文地址:https://www.cnblogs.com/muahao/p/7489254.html
Copyright © 2011-2022 走看看