关于内存字节大小的测试,用sizeof();

来源:互联网 发布:java bytebuffer mark 编辑:程序博客网 时间:2024/06/08 10:02

各个变量在 计算内存中占有的字节大小为多少,最近由于学算法,然后进行了简单的测试。

sizeof()函数:返回对象或者类型所占的字节数,其返回值类型为size_t,在头文件stddef.h中定义。

测试代码(C++):

#include <iostream>using namespace std;int main(){        cout    << "the byte of char is :  "<< sizeof(char)<<"\n"                << "the byte of int is :  "<< sizeof(int)<<"\n"                << "the byte of unsigned is :  "<< sizeof(unsigned)<<"\n"                << "the byte of double is :  "<< sizeof(double)<<"\n"                << "the byte of long double is :  "<< sizeof(long double)<<"\n"                << "the byte of float is :  "<< sizeof(float)                <<endl;        return 0;}

测试结果如下:

the byte of char is :  1the byte of int is :  4the byte of unsigned is :  4the byte of double is :  8the byte of long double is :  16the byte of float is :  4

 此代码亦可以用C来写,直接用printf函数,如下

printf("the byte of int/unsigned/double/long double/float is \t%d\t%d\t%d\t%d\t%d\n",sizeof(int),sizeof(unsigned),sizeof(long),sizeof(long double),sizeof(float));

附注:

1、计算机上的所有数据都是以“位”(bit)来存储的,1bit就代表一个0或1;

2、字节(byte):8bit=1byte,一个英文字母占一个字节,一个汉字占用两个字节。一般情况下,bit用小写“b”表示,byte用大写“B”表示。

3、1KB=1024B ,1MB=1024KB,1G=1024MB。

4、1万汉字的小说,要用多少内存才能存储?10万汉字*2B=200'000B=195.3KB=0.19MB,如果仅仅简单估算的话,假定1KB=1000B,那么10万汉字占用的内存就是200KB,约0.2MB。

5、一般的网络速度衡量单位都是“位每秒”(bps)。