Variable size/Get: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 6:
=={{header|11l}}==
<
print(T(i).size)
print(Int64.size)</
{{out}}
Line 18:
=={{header|ActionScript}}==
Requires the debug Flash Player 9.0.115.0 or higher.
<syntaxhighlight lang="actionscript">
package {
Line 51:
}
</syntaxhighlight>
=={{header|Ada}}==
Ada represents the size of a variable in bits, not bytes like many other languages.
<
Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element</
=={{header|ALGOL 68}}==
Line 68:
Also note that the size of a '''byte''' can vary from one [[wp:CPU|CPU]] to another, c.f. [[Host_introspection#ALGOL_68]] for additional details.
<
STRING s:="DCLXVI", [666]CHAR c;
print((
Line 74:
"UPB STRING s =",UPB s, new line,
"UPB []CHAR c =",UPB c, new line
))</
{{out}}
<pre>
Line 83:
=={{header|AutoHotkey}}==
<
MsgBox % size := VarSetCapacity(Var) ; 10240000</
=={{header|Babel}}==
In Babel, you can get the raw size with the mu operator and you can also
break this down into its components:
<
{ (1 2 (3 4) 5 6)
dup mu disp
Line 100:
disp! : { %d cr << }
</syntaxhighlight>
{{out}}
<pre>
Line 126:
You can also take the size of an object by first serializing it:
<
</syntaxhighlight>
{{out}}
38
=={{header|BASIC}}==
<
20 PRINT LEN(variable$)</
{{works with|QBasic}}
Line 139:
Many BASICs, especially those compatible with [[QBasic]],
can use <code>LEN</code> to find the size of any variable:
<
PRINT LEN(a), LEN(b), LEN(c), LEN(d), LEN(e)</
{{out}}
Line 151:
<code>TypeOf</code> returns a number representing the type of value that was passed:
<
f = 1.0 #Float
s$ = "cad" #String
Line 162:
print typeof(s$) # 3
print typeof(A) # 4
print typeof(m) # 6</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
A variable's size is implied by its type suffix. The easiest way to determine the size is to use a structure:
<
DIM istruct{i%}
DIM fstruct{f}
Line 177:
PRINT "Size of f is ";DIM(fstruct{})
PRINT "Size of d# is ";DIM(dstruct{})
PRINT "Size of s$ is ";DIM(sstruct{})</
Here the size given for the string s$ is for its descriptor, not its contents.
Line 190:
=={{header|C}}==
<
=={{header|C sharp|C#}}==
<
class Program
{
Line 203:
}
}
</syntaxhighlight>
=={{header|C++}}==
Store the size of an int in bytes:
<
std::size_t intsize = sizeof(int);</
Note: sizeof can be used without the header <cstdlib>; the latter is only needed for the type std::size_t, which is an alias for whatever type is used to store sizes for the given compiler.
Output the number of bits of an int:
<
#include <cstdlib>
std::size_t intbits = CHAR_BITS*sizeof(int);</
Note: the type char is always 1 byte (which, however, need not be 8 bits).
Line 222:
Get the size of a variable in bytes:
<
int a = 1;
std::size_t a_size = sizeof a;</
Note: Parentheses are needed around types, but not around variables.
Line 230:
Get the size of an expression's type:
<
std::size_t size = sizeof (3*6 + 7.5);</
=={{header|COBOL}}==
Line 255:
Directing Facility <code>>>IF P64 IS SET</code>, shown here.
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol">
identification division.
program-id. variable-size-get.
Line 317:
goback.
end program variable-size-get.
</syntaxhighlight>
{{out}}
Line 377:
{{works with|LispWorks}}
<
(b (make-array 10))
(c "a string"))
(list (hcl:find-object-size a)
(hcl:find-object-size b)
(hcl:find-object-size c)))</
returns
<syntaxhighlight lang
However, note that interesting objects are generally composed of several levels of references, often including references to preexisting objects, so what the size should be considered as is often hard to define after the fact. A robust though non-automatic way to determine the “true” memory utilization of some data is to do something like this:
<
(gc) ; name varies by implementation
(room)
Line 395:
(push (allocate-something-of-interest) items))
(gc)
(room))</
[http://www.lispworks.com/documentation/HyperSpec/Body/f_room.htm room] prints information about current memory usage, but in an implementation-defined format. Take the difference of the relevant numbers, divide by 512, and you have the amount of memory consumed by allocating one additional instance of whatever it is.
Line 401:
=={{header|D}}==
Every type and variable in D has a property <tt>sizeof</tt>, which give the size of the type in bytes. eg.
<
writefln(i.sizeof) ; // print 4
int[13] ints1 ; // static integer array of length 13
Line 407:
int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13
writefln(ints2.sizeof) ; // print 8, all dynamic array has this size
writefln(ints2.length) ; // print 13, length is the number of allocated element in aggregated type</
=={{header|Delphi}}==
<
=={{header|Elixir}}==
When “counting” the number of elements in a data structure, Elixir also abides by a simple rule: the function is named '''size''' if the operation is in constant time or '''length''' if the operation is linear.
<
IO.puts length(list) #=> 3
Line 435:
map = Map.new([{:b, 1}, {:a, 2}])
IO.puts map_size(map) #=> 2</
=={{header|Erlang}}==
Line 450:
=={{header|Factor}}==
<
! Show size in bytes
Line 460:
! Show number of bits in a fixnum
fixnum-bits . ! 60</
=={{header|Forth}}==
{{works with|ANS/ISO Forth}}
Forth is very close to the metal. Forth 94 standardized the size of an integer to be the native integer size of the CPU. Forth refers to this as a CELL. The defining word VARIABLE creates a variable that is one cell wide. The word CELLS takes an integer parameter and returns the number of bytes in one CELL.
<
VARIABLE X ( creates a variable 1 cell wide)</
Test at the GNU Forth (32bit) console
<
4 Bytes ok
-1 X ! ok
HEX X @ U. FFFFFFFF ok</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
The intrinsic functions bit_size and digits can be used to find the size of an integer. Bit_size returns the number of bits in an integer while digits returns the number of significant digits in the integer. Because of the use of signed integers this will be one less than the bit size. Digits can be used on real variables where it returns the number of significant figures in the mantissa.
<
INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4)
INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8)
Line 489:
WRITE (*,*) BIT_SIZE(fourbytes), DIGITS(fourbytes) ! prints 32 and 31
WRITE (*,*) BIT_SIZE(eightbytes), DIGITS(eightbytes) ! prints 64 and 63
WRITE (*,*) DIGITS(0.0), DIGITS(0d0) ! prints 24 and 53</
=={{header|Free Pascal}}==
Line 498:
=={{header|FreeBASIC}}==
<
Dim i As Integer
Line 518:
Print "Press any key to quit"
Sleep
</syntaxhighlight>
{{out}}
Line 533:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=87f102023bd9ef6dbd52b0158be2c3ee Click this link to run this code]'''
<
Print "Boolean =\t " & SizeOf(gb.Boolean)
Line 548:
Print "Variant =\t " & SizeOf(gb.Variant)
End</
Output:
<pre>
Line 566:
=={{header|Go}}==
<
unsafe.Sizeof(x)</
More detail:
<
import (
Line 594:
// Some sizes are implementation dependent.
fmt.Println(runtime.Version(), runtime.GOARCH)
}</
{{out}}
<pre>
Line 606:
=={{header|Haskell}}==
only works with types that instance Storable:
<
sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine)
sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine)
sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine)
sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine)</
=={{header|Icon}} and {{header|Unicon}}==
Line 623:
** This will show 0 for the assignment of program constants such as strings. Manipulation will be required to produce an allocation.
<
record rec4(a,b,c,d)
Line 651:
write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0)
}
end</
{{out}}
Line 674:
IDL is array based, so its <tt>size()</tt> function is geared towards that:
<
print,size(arr)
;=> prints this:
2 3 4 2 12</
The result means: 2 dimensions in the array, the first dimension has extent 3, the second has extent 4, the elements of the array are 2-byte integers (IDL's default for an "int"), there's a total of 12 elements in the array.
Line 686:
For example:
<
7!:5<'some_variable'</
An advantage of <code>7!:5</code> is that it can be used on any name, including functions, operators, etc (i.e. it's not just restricted to variables):
<
7!:5<'some_function'</
=={{header|Julia}}==
<
1
Line 700:
julia> sizeof(t)
8</
(The last line returns 4 on a 32-bit machine or when Julia is compiled in 32-bit mode.)
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 715:
println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes")
println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes")
}</
{{out}}
Line 729:
=={{header|Lasso}}==
<
mystring = 'Hello World',
myarray = array('one', 'two', 3),
Line 750:
//#myinteger -> size // will fail
// an integer can however be converted to a string first
string(#myinteger) -> size</
->11
Line 759:
4
=={{header|Lua}}==
<
> print(#s)
5
> t = { 1,2,3,4,5 }
> print(#t)
5</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre>64</pre>
Line 774:
BITSIZE and BYTESIZE are built in functions.
<
FROM IO IMPORT Put;
Line 782:
Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n");
Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n");
END Size.</
{{out}}
Line 791:
=={{header|Nim}}==
<
=={{header|NS-HUBASIC}}==
Note: This only works with strings.
<syntaxhighlight lang
=={{header|OCaml}}==
<
The word size in octet can be found with (Sys.word_size / 8).
(The size of all the datas in OCaml is at least one word, even chars and bools.)
Line 822:
in
fst(rec_size [] (Obj.repr v))
;;</
testing in the toplevel:
<
- : int = 1
Line 909:
# sizeof(Array.init 10 (fun _ -> String.create 20)) ;;
- : int = 61</
=={{header|Ol}}==
Line 925:
=={{header|PARI/GP}}==
In GP, this gets the size of the variable x in bytes:
<syntaxhighlight lang
In PARI,
<syntaxhighlight lang
returns the length of the variable x in words. <code>gsizebyte</code> and <code>gsizeword</code> are also available.
Line 938:
{{works with|Perl|5.28}}
{{libheader|Devel::Size}}
<
my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
print size($var); # 24
print total_size(\@arr); # 256</
=={{header|Phix}}==
<!--<
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"An integer contains %d bytes.\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
<!--</
See builtins\VM\pHeap.e for the complete low-level details. Because of shared references,
it is often not practical to obtain a meaningful size, and you can often store a "sparse"
Line 966:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
/* whatever data type or structure it is. */
Line 975:
/* varying-length string, including its */
/* length field. */
</syntaxhighlight>
=={{header|Pop11}}==
Line 983:
Form user point of view more important is space taken by values (size of values referenced by a single variable typically varies during program execution). The datasize function gives amount (in machine words) of space directly used by given value:
<
datasize(12) =>
;;; Prints 3: 3 character fits into single machine word, 1 word
Line 992:
datasize({1 2 3}) =>
;;; Prints 3 because only first node counts
datasize([1 2 3]) =></
Note that large amount of data my be referenced from given value, but this data is potentially shared, so there is no canonical way to assign it to a single value or variable.
=={{header|PureBasic}}==
<
Debug SizeOf(a)
; This also works for structured variables</
=={{header|Python}}==
This information is only easily available for the array type:
<
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
Line 1,017:
array('l', [1, 2, 3, 4, 5]) Size = 20
array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24
>>></
Also:
{{works with|Python|2.6+}}
<
sys.getsizeof(obj)</
=={{header|R}}==
object.size gives '''an estimate''' of the amount of memory used to store the variable, in (kilo/Mega/Giga) bytes. See also dim, length and nchar for determining the extent of mulitdimensional variables (such as matrices, lists, etc).
<
num <- c(1, 3, 6, 10)
object.size(num) # e.g. 56 bytes
Line 1,038:
l2 <- list(num, num2)
object.size(l2) # e.g. 128 bytes</
=={{header|Racket}}==
<
#lang racket
(require ffi/unsafe)
Line 1,047:
(begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
(sizes _byte _short _int _long _llong _float _double)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
Raku tries to avoid generic terms such as "size" and "length", instead providing methods that are expressed in terms of the units appropriate to the abstraction level.
<syntaxhighlight lang="raku"
my $string = "abc";
Line 1,063:
my $buffer = '#56997; means "four dragons".'.encode('utf8');
say $buffer.bytes; # 26
say $buffer.elems; # 26</
Raku's Int type is arbitrary sized, and therefore the abstract size of the integer depends on how many bits are needed to represent it. While the internal representation is likely to be "chunky" by 32 or 64 bits, this is considered an implementation detail and is not revealed to the programmer.
Line 1,071:
In REXX, you simply set a variable to a value (it could be an expression);
<br>the value's length is the size of the variable's value.
<
/* to find the size (length) of the value of a REXX variable. */
Line 1,130:
│ The "k" loop uses 21,777,792 bytes for the compound variables, │
│ (excluding the DO loop indices [j and k] themselves). │
└────────────────────────────────────────────────────────────────────┘*/</
=={{header|Ring}}==
<
list1 = list(2)
list2 = list(4)
Line 1,145:
see "Size of list4 is : " + len(list4) + nl
see "Size of list5 is : " + len(list5) + nl
</syntaxhighlight>
Output:
<pre>
Line 1,158:
Almost all objects in Ruby (MRI) take 40 bytes (on a x64 machine) initially. Sometimes this is enough to store the entire object, sometimes additional memory has to be allocated. For strings that is the case if they are longer than 23 chars. The additional memory can be retrieved using 'ObjectSpace':
<
require 'objspace'
Line 1,164:
p ObjectSpace.memsize_of("a"*24) #=> 25
p ObjectSpace.memsize_of("a"*1000) #=> 1001
</syntaxhighlight>
=={{header|Rust}}==
<
fn main() {
Line 1,177:
assert_eq!(6, mem::size_of_val(&arr));
}
</syntaxhighlight>
=={{header|Scala}}==
{{libheader|Scala}}<
val primitives: List[(Any, Long)] =
Line 1,188:
(Long, Long.MaxValue))
primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes"))</
{{out}}
<pre>A Scala Byte has 1 bytes
Line 1,196:
=={{header|Swift}}==
<syntaxhighlight lang
More detail:
<
println(sizeof(Int))
var i: Int = 42
Line 1,206:
// the same number, the size of the String struct.
println(sizeofValue("Rosetta"))
println(sizeofValue("Code"))}</
{{out}}
<pre>
Line 1,217:
=={{header|Tcl}}==
Since all variables are ultimately strings in Tcl, this is easy:
<syntaxhighlight lang
There is additional overhead per value and per variable, which depends on the architecture that Tcl was built for and the version of Tcl. In 8.5 on a ILP-32 architecture, local variables have an overhead of 8 bytes (without traces) and values have a minimum overhead of 24 bytes (this minimum is achieved for integers that fit in a signed 64-bit integer type or a double-precision float).
Line 1,225:
There are two primary data types in Toka, cells and characters. The size of these can be obtained easily:
<
cell-size .</
If you load the floating point support, you can also obtain the size of a floating point number:
<
float-size .</
All sizes are returned in bytes.
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT,{}
string="somerandomstring"
Line 1,245:
PRINT "has size: ",size
PRINT "and length: ",length
</syntaxhighlight>
{{out}}
<pre>
Line 1,299:
The <code>struct</code> size corresponds to the size of the C struct
<
uint32_t x : 17;
uint8_t y : 3;
char z[16];
};</
as calculated by the GNU C compiler on the same platform. The `uint32_t` leading bitfield creates a minimum alignment of four bytes. The `y` bitfield is packed into the third byte of the structure, and the `z` array starts on the fourth, ending on the nineteenth. The alignment requirement pads the structure to 20.
Line 1,331:
=={{header|UNIX Shell}}==
<
# as for finding the length of a string:
greeting='Hello, world!'
greetinglength=`printf '%s' "$greeting" | wc -c`
echo "The greeting is $greetinglength characters in length"</
=={{header|Ursala}}==
Line 1,351:
and returns the number of bits of precision in the mantissa.
Host memory usage is linear plus a small constant.
<
#cast %nL
examples = <weight 'hello',mpfr..prec 1.0E+0></
{{out}}
<pre>
Line 1,362:
=={{header|Vala}}==
<
/* you can replace the int below with any of the vala supported datatypes
see the vala documentation for valid datatypes.
*/
print(@"$(sizeof(int))\n");
}</
=={{header|Vlang}}==
<syntaxhighlight lang="text">sizeof(i64)</
{{out}}
<pre>8</pre>
Line 1,381:
=={{header|Yabasic}}==
<code>frnfn_size</code> return the size (in bytes) of one of the types available for foreign function calls.
<
print frnfn_size("int8") //1
print frnfn_size("uint16") //2
Line 1,393:
print frnfn_size("char") //1
print frnfn_size("int") //4
print frnfn_size("short") //2</
=={{header|XPL0}}==
Line 1,407:
for dynamic integer arrays using the Reserve intrinsic.
<
int Size;
int A, B;
Line 1,415:
Size:= addr Y - addr X;
IntOut(0, Size); CrLf(0);
]</
{{out}}
Line 1,424:
=={{header|zkl}}==
<
(0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int
(1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float
Line 1,431:
Dictionary("1",1, "2",2).len() //-->2 (keys)
Data(0,Int,1,2,3,4).len() //-->4 (bytes)
Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ)</
Put the data into a variable, same results: a:=123; a.len() --> 1
|