zoukankan      html  css  js  c++  java
  • 文件大小的友好输出及其 Python 实现

    在数据库中存储时,使用 Bytes 更精确,可扩展性和灵活性都很高。

    输出时,需要做一些适配。

    1. 注意事项与测试代码

    1. 需要考虑 sizeInBytes 为 None 的场景。
    2. 除以 1024.0 而非 1024,避免丢失精度。

    实现的函数为 getSizeInMb(sizeInBytes),通用的测试代码为

    def getSizeInMb(sizeInBytes):
        return 0
    
    def test(sizeInBytes):
        print '%s -> %s' % (sizeInBytes, getSizeInMb(sizeInBytes))
    
    test(None)
    test(0)
    test(10240000)
    test(1024*1024*10)

    2. 以 MB 为单位输出 -- 返回 float

        通常,电子书的大小在 1 - 50MB 之间,输出时统一转为 MB 是不错的选择。

    弊端:

    1. 输出精度过高,比如 10240000 Bytes 计算结果为 10240000 -> 9.765625
    2. 文件大小有限制,小于 1 MB 或 G 级数据不适合该方式展示

    优势:

    1. 适合于用返回值参与计算
    def getSizeInMb(sizeInBytes):
        return (sizeInBytes or 0) / (1024.0*1024.0)

    3. 以 MB 为单位保留 1 位小数 -- 返回 str

    处于精度问题考虑,可以选择保留 1 位小数。

    def getSizeInMb(sizeInBytes):
        return '%.1f' % ((sizeInBytes or 0) / (1024.0*1024.0), )  # use 1-dimension tuple is suggested

    返回值建议写成 '%.1f' % (number,)  而非  '%.1f' % (number)

    二者均能正确执行,但后者容易被误判为执行只有一个参数 number 的函数,导致难以判断的错误。

    3. 以 MB 为单位保留至多 1 位小数 -- 返回 str

    大多数操作系统一般展示至多 1 位小数

    def getSizeInMb(sizeInBytes):
        sizeInMb = '%.1f' % ((sizeInBytes or 0) / (1024.0*1024.0), )  # use 1-dimension tuple is suggested
        return sizeInMb[:-2] if sizeInMb.endswith('.0') else sizeInMb  # python2.5+ required

    4. 自动选择最佳单位

    def getSizeInNiceString(sizeInBytes):
        """
        Convert the given byteCount into a string like: 9.9bytes/KB/MB/GB
        """
        for (cutoff, label) in [(1024*1024*1024, "GB"),
                                (1024*1024, "MB"),
                                (1024, "KB"),
                                ]:
            if sizeInBytes >= cutoff:
                return "%.1f %s" % (sizeInBytes * 1.0 / cutoff, label)
    
        if sizeInBytes == 1:
            return "1 byte"
        else:
            bytes = "%.1f" % (sizeInBytes or 0,)
            return (bytes[:-2] if bytes.endswith('.0') else bytes) + ' bytes'

    算法说明:

    1. 从英语语法角度,只有 1 使用单数形式。其他 0/小数 均使用复数形式。涉及 bytes 级别

    2. 精度方面,KB 及以上级别,保留 1 位小数。bytes 保留至多 1 位小数。

        这种处理规则,不适合于小数十分位为 0 的情况,比如 10.0 bytes,10.01 bytes。输入结果均为 10 bytes。

        其他情况下,精度均不存在问题。

    测试数据与结果如下图

  • 相关阅读:
    通信原理
    java实现聊天室的简单实现
    计算机网络笔记——第四章、网络层
    泛型高级之通配符
    看文档总结
    HashSet源码解析
    HashTable源码解析
    计算机网络笔记——第三章、数据链路层
    Collection集合的功能
    第六章 应用层
  • 原文地址:https://www.cnblogs.com/misspy/p/3661770.html
Copyright © 2011-2022 走看看