更高效的字节转换?-安卓沙马林C#

更高效的字节转换?-安卓沙马林C#,c#,android,xamarin,type-conversion,calculation,C#,Android,Xamarin,Type Conversion,Calculation,是否有人知道一种更有效的方法来执行此代码: public static float ConvertTrafficValues(double bytes, out string speedBytes) { if (bytes >= 1000000) { bytes /= 1000000; bytes = Math.Round(bytes, 1); speedBytes = "MB/

是否有人知道一种更有效的方法来执行此代码:

public static float ConvertTrafficValues(double bytes, out string speedBytes)
    {
        if (bytes >= 1000000)
        {
            bytes /= 1000000;
            bytes = Math.Round(bytes, 1);
            speedBytes = "MB/s";
        }
        else if (bytes >= 1000)
        {
            bytes /= 1000;
            bytes = Math.Round(bytes, 0);
            speedBytes = "KB/s";
        }
        else
        {
            bytes = Math.Round(bytes, 0);
            speedBytes = "B/s";
        }

        return (float)bytes;
    }

我每秒都会打多次电话,同时还有其他一些事情,我需要它尽可能高效

我根据公认的答案编写了以下解决方案:


即使涉及到文件卷,底层逻辑也几乎相同。我将最大值限制为
Mb
,因为这就是您的方法所做的。我没有更改您的实现逻辑,因为您应该比我更了解如何以及何时使用该方法。

这是关于类似的主题。我不使用该网站-甚至不确定这是关于什么的,这正是针对这些类型的问题。对我来说,这似乎是一个开始使用它的好时机。将此例程称为“每秒多次”对于效率和性能来说都是不错的。每秒调用这个函数100次甚至不会增加CPU的负载。我们的产品中有类似的代码来更新显示器上的比特率……问题是,我需要它是电池效率的,因为它是一个持续的后台任务,它正在被更新。在以一百万个for循环周期的不同顺序进行一些测试之后,您的代码似乎比我最初编写的代码(110-120)慢得多(570ms)。它可能与数学有关。Pow也许?
private static readonly string[] s_Suffixes = { "B/s", "KB/s", "MB/s" };

public static Single ConvertTrafficValues(Double bytes, out String speedBytes)
{
    if (bytes == 0.0d)
    {
        speedBytes = "B/s";
        return 0.0f;
    }

    Int32 magnitude = (Int32)Math.Log(bytes, 1024.0d);
    Double size;

    if (magnitude >= (s_Suffixes.Length - 1))
    {
        magnitude = s_Suffixes.Length - 1;
        size = bytes / Math.Pow(2.0d, magnitude * 10);
    }
    else
    {
        size = bytes / Math.Pow(2.0d, magnitude * 10);

        if (Math.Round(size, 2) >= 1000.0d)
        {
            magnitude += 1;
            size /= 1024.0d;
        }
    }

    speedBytes = s_Suffixes[magnitude];

    return (Single)size;
}