Hướng dẫn how do i print the size of a data type in python? - làm cách nào để in kích thước của kiểu dữ liệu trong python?

Làm cách nào để xác định kích thước của một đối tượng trong Python?

Câu trả lời, "Chỉ cần sử dụng sys.getsizeof", không phải là một câu trả lời hoàn chỉnh.

Câu trả lời đó hoạt động trực tiếp cho các đối tượng tích hợp, nhưng nó không tính đến những gì các đối tượng đó có thể chứa, cụ thể, các loại nào, chẳng hạn như đối tượng tùy chỉnh, bộ dữ liệu, danh sách, dicts và bộ chứa. Chúng có thể chứa các thể hiện lẫn nhau, cũng như số, chuỗi và các đối tượng khác.

Một câu trả lời đầy đủ hơn

Sử dụng Python 3.6 64 bit từ phân phối Anaconda, với sys.getsizeof, tôi đã xác định kích thước tối thiểu của các đối tượng sau đây và lưu ý rằng các thiết lập và định hướng không gian để không phát triển lại cho đến khi một số lượng được đặt (có thể thay đổi bằng cách thực hiện ngôn ngữ):

Python 3:

Empty
Bytes  type        scaling notes
28     int         +4 bytes about every 30 powers of 2
37     bytes       +1 byte per additional byte
49     str         +1-4 per additional character (depending on max width)
48     tuple       +8 per additional item
64     list        +8 for each additional
224    set         5th increases to 736; 21nd, 2272; 85th, 8416; 341, 32992
240    dict        6th increases to 368; 22nd, 1184; 43rd, 2280; 86th, 4704; 171st, 9320
136    func def    does not include default args and other attrs
1056   class def   no slots 
56     class inst  has a __dict__ attr, same scaling as dict above
888    class def   with slots
16     __slots__   seems to store in mutable tuple-like structure
                   first slot grows to 48, and so on.

Làm thế nào để bạn giải thích điều này? Vâng, nói rằng bạn có một bộ với 10 mục trong đó. Nếu mỗi mục là 100 byte, toàn bộ cấu trúc dữ liệu lớn như thế nào? Bộ này là 736 vì nó đã tăng kích thước một lần lên 736 byte. Sau đó, bạn thêm kích thước của các mục, vì vậy tổng cộng 1736 byte

Một số cảnh báo cho các định nghĩa chức năng và lớp học:

Lưu ý mỗi định nghĩa lớp có cấu trúc proxy __dict__ (48 byte) cho các lớp attrs. Mỗi khe có một mô tả (như property) trong định nghĩa lớp.

Các trường hợp có rãnh bắt đầu với 48 byte trên phần tử đầu tiên của chúng và tăng thêm 8 mỗi. Chỉ các đối tượng có rãnh trống có 16 byte và một thể hiện không có dữ liệu có rất ít ý nghĩa.

Ngoài ra, mỗi định nghĩa hàm có các đối tượng mã, có thể là tài liệu và các thuộc tính có thể khác, thậm chí là __dict__.

Cũng lưu ý rằng chúng tôi sử dụng

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
1 vì chúng tôi quan tâm đến việc sử dụng không gian cận biên, bao gồm chi phí thu gom rác cho đối tượng, từ các tài liệu:

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
2 gọi phương thức đối tượng
    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
3 và thêm một trình thu gom rác bổ sung nếu đối tượng được quản lý bởi người thu gom rác.

Cũng lưu ý rằng việc thay đổi kích thước danh sách (ví dụ: nối lại một cách lặp lại cho họ) khiến chúng phân bổ không gian, tương tự như các bộ và dicts. Từ mã nguồn listobj.c:

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);

Dữ liệu lịch sử

Phân tích Python 2.7, được xác nhận với

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
4 và sys.getsizeof:

Bytes  type        empty + scaling notes
24     int         NA
28     long        NA
37     str         + 1 byte per additional character
52     unicode     + 4 bytes per additional character
56     tuple       + 8 bytes per additional item
72     list        + 32 for first, 8 for each additional
232    set         sixth item increases to 744; 22nd, 2280; 86th, 8424
280    dict        sixth item increases to 1048; 22nd, 3352; 86th, 12568 *
120    func def    does not include default args and other attrs
64     class inst  has a __dict__ attr, same scaling as dict above
16     __slots__   class with slots has no dict, seems to store in 
                    mutable tuple-like structure.
904    class def   has a proxy __dict__ structure for class attrs
104    old class   makes sense, less stuff, has real dict though.

Lưu ý rằng từ điển (nhưng không phải bộ) có một biểu diễn nhỏ gọn hơn trong Python 3.6

Tôi nghĩ rằng 8 byte cho mỗi mục bổ sung để tham khảo có rất nhiều ý nghĩa trên máy 64 bit. 8 byte đó chỉ vào vị trí trong bộ nhớ, mục chứa ở. 4 byte có chiều rộng cố định cho unicode trong Python 2, nếu tôi nhớ lại chính xác, nhưng trong Python 3, STR trở thành một unicode có chiều rộng bằng chiều rộng tối đa của các ký tự.

Và để biết thêm về các khe, xem câu trả lời này.

Một chức năng hoàn chỉnh hơn

Chúng tôi muốn một hàm tìm kiếm các yếu tố trong danh sách, bộ dữ liệu, bộ, dicts, ________ 16 và

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
7, cũng như những điều khác mà chúng tôi có thể chưa nghĩ đến.

Chúng tôi muốn dựa vào

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
8 để thực hiện tìm kiếm này vì nó hoạt động ở cấp độ C (làm cho nó rất nhanh). Nhược điểm là get_referents có thể trả lại các thành viên dự phòng, vì vậy chúng tôi cần đảm bảo chúng tôi không tăng gấp đôi.

Các lớp, mô -đun và chức năng là những người độc thân - chúng tồn tại một lần trong bộ nhớ. Chúng tôi không quan tâm đến quy mô của họ, vì chúng tôi không thể làm gì nhiều về họ - họ là một phần của chương trình. Vì vậy, chúng tôi sẽ tránh đếm chúng nếu chúng được tham chiếu.

Chúng tôi sẽ sử dụng một danh sách đen các loại để chúng tôi không bao gồm toàn bộ chương trình trong số lượng kích thước của chúng tôi.

import sys
from types import ModuleType, FunctionType
from gc import get_referents

# Custom objects know their class.
# Function objects seem to know way too much, including modules.
# Exclude modules as well.
BLACKLIST = type, ModuleType, FunctionType


def getsize(obj):
    """sum size of object & members."""
    if isinstance(obj, BLACKLIST):
        raise TypeError('getsize() does not take argument of type: '+ str(type(obj)))
    seen_ids = set()
    size = 0
    objects = [obj]
    while objects:
        need_referents = []
        for obj in objects:
            if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids:
                seen_ids.add(id(obj))
                size += sys.getsizeof(obj)
                need_referents.append(obj)
        objects = get_referents(*need_referents)
    return size

Để đối chiếu điều này với chức năng danh sách trắng sau đây, hầu hết các đối tượng đều biết cách tự đi qua mục đích của bộ sưu tập rác (đó là những gì chúng ta đang tìm kiếm khi chúng ta muốn biết mức độ đắt tiền trong bộ nhớ một số đối tượng.

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
8.) Tuy nhiên, biện pháp này sẽ mở rộng hơn nhiều so với dự định nếu chúng ta không cẩn thận.

Ví dụ, các chức năng biết khá nhiều về các mô -đun mà chúng được tạo ra.

Một điểm tương phản khác là các chuỗi có khóa trong từ điển thường được thực tập nên chúng không được nhân đôi. Kiểm tra

Bytes  type        empty + scaling notes
24     int         NA
28     long        NA
37     str         + 1 byte per additional character
52     unicode     + 4 bytes per additional character
56     tuple       + 8 bytes per additional item
72     list        + 32 for first, 8 for each additional
232    set         sixth item increases to 744; 22nd, 2280; 86th, 8424
280    dict        sixth item increases to 1048; 22nd, 3352; 86th, 12568 *
120    func def    does not include default args and other attrs
64     class inst  has a __dict__ attr, same scaling as dict above
16     __slots__   class with slots has no dict, seems to store in 
                    mutable tuple-like structure.
904    class def   has a proxy __dict__ structure for class attrs
104    old class   makes sense, less stuff, has real dict though.
0 cũng sẽ cho phép chúng tôi tránh đếm các bản sao, mà chúng tôi làm trong phần tiếp theo. Giải pháp danh sách đen bỏ qua các khóa đếm hoàn toàn là chuỗi.

Các loại danh sách trắng, khách truy cập đệ quy

Để tự mình bao gồm hầu hết các loại này, thay vì dựa vào mô -đun

Bytes  type        empty + scaling notes
24     int         NA
28     long        NA
37     str         + 1 byte per additional character
52     unicode     + 4 bytes per additional character
56     tuple       + 8 bytes per additional item
72     list        + 32 for first, 8 for each additional
232    set         sixth item increases to 744; 22nd, 2280; 86th, 8424
280    dict        sixth item increases to 1048; 22nd, 3352; 86th, 12568 *
120    func def    does not include default args and other attrs
64     class inst  has a __dict__ attr, same scaling as dict above
16     __slots__   class with slots has no dict, seems to store in 
                    mutable tuple-like structure.
904    class def   has a proxy __dict__ structure for class attrs
104    old class   makes sense, less stuff, has real dict though.
1, tôi đã viết chức năng đệ quy này để cố gắng ước tính kích thước của hầu hết các đối tượng Python, bao gồm hầu hết các loại tích hợp, loại trong mô -đun bộ sưu tập và các loại tùy chỉnh (có rãnh và mặt khác) .

Loại chức năng này mang lại sự kiểm soát hạt mịn hơn nhiều đối với các loại chúng ta sẽ tính cho việc sử dụng bộ nhớ, nhưng có nguy cơ bỏ các loại quan trọng:

import sys
from numbers import Number
from collections import deque
from collections.abc import Set, Mapping


ZERO_DEPTH_BASES = (str, bytes, Number, range, bytearray)


def getsize(obj_0):
    """Recursively iterate to sum size of object & members."""
    _seen_ids = set()
    def inner(obj):
        obj_id = id(obj)
        if obj_id in _seen_ids:
            return 0
        _seen_ids.add(obj_id)
        size = sys.getsizeof(obj)
        if isinstance(obj, ZERO_DEPTH_BASES):
            pass # bypass remaining control flow and return
        elif isinstance(obj, (tuple, list, Set, deque)):
            size += sum(inner(i) for i in obj)
        elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
            size += sum(inner(k) + inner(v) for k, v in getattr(obj, 'items')())
        # Check for custom object instances - may subclass above too
        if hasattr(obj, '__dict__'):
            size += inner(vars(obj))
        if hasattr(obj, '__slots__'): # can have __slots__ with __dict__
            size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s))
        return size
    return inner(obj_0)

Và tôi đã thử nghiệm nó khá tình cờ (tôi nên nhất quán):

>>> getsize(['a', tuple('bcd'), Foo()])
344
>>> getsize(Foo())
16
>>> getsize(tuple('bcd'))
194
>>> getsize(['a', tuple('bcd'), Foo(), {'foo': 'bar', 'baz': 'bar'}])
752
>>> getsize({'foo': 'bar', 'baz': 'bar'})
400
>>> getsize({})
280
>>> getsize({'foo':'bar'})
360
>>> getsize('foo')
40
>>> class Bar():
...     def baz():
...         pass
>>> getsize(Bar())
352
>>> getsize(Bar().__dict__)
280
>>> sys.getsizeof(Bar())
72
>>> getsize(Bar.__dict__)
872
>>> sys.getsizeof(Bar.__dict__)
280

Việc thực hiện này phá vỡ các định nghĩa và định nghĩa chức năng của lớp vì chúng tôi không theo đuổi tất cả các thuộc tính của chúng, nhưng vì chúng chỉ nên tồn tại một lần trong bộ nhớ cho quá trình, kích thước của chúng thực sự không quan trọng quá nhiều.

Làm thế nào để bạn kiểm tra kích thước dữ liệu trong Python?

Pandas: Nhận số lượng hàng, cột, tất cả các phần tử (kích thước) của DataFrame..
Hiển thị số lượng hàng, cột, vv .: df.info ().
Nhận số lượng hàng: Len (DF).
Nhận số lượng cột: Len (df.columns).
Nhận số lượng hàng và cột: DF.Shape ..
Nhận số lượng các yếu tố: df.size ..
Ghi chú khi chỉ định chỉ số ..

Kích thước của loại dữ liệu trong Python là gì?

Các quy định được hỗ trợ: 8, 16, 32 (mặc định) và 64 bit.8, 16, 32 (default) and 64 bits.

Làm thế nào để bạn in kiểu dữ liệu trong Python?

Làm thế nào để in loại biến trong Python.Để có được loại biến trong Python, bạn có thể sử dụng hàm loại tích hợp ().Trong Python, mọi thứ đều là một đối tượng.Vì vậy, khi bạn sử dụng hàm loại () để in loại giá trị được lưu trữ trong một biến cho bàn điều khiển, nó sẽ trả về loại lớp của đối tượng.use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

Làm cách nào để in kích thước int trong python?

Để có được độ dài của một số nguyên trong python: sử dụng lớp str () để chuyển đổi số nguyên thành chuỗi, ví dụ:result = str (my_int) .Pass chuỗi vào hàm len (), ví dụ:Len (my_str).Hàm Len () sẽ trả về độ dài của chuỗi.Use the str() class to convert the integer to a string, e.g. result = str(my_int) . Pass the string to the len() function, e.g. len(my_str) . The len() function will return the length of the string.