-1

Does anyone know a more efficient way of doing this code:

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;
    }

Im calling this multiple times every second alongside with some other things and I need it to be as efficient as possible

Nevaran
  • 137
  • 9
  • This is more on topic for something like https://codereview.stackexchange.com. – itsme86 Jan 05 '18 at 22:44
  • I dont use that site though - not even sure what that is about – Nevaran Jan 05 '18 at 22:56
  • It's for exactly these types of questions. Seems like a good time to start using it to me. – itsme86 Jan 05 '18 at 22:56
  • Calling this routine "multiple times every second" will be fine for efficiency and performance concerns. Calling this function 100 times per second won't even raise the load on your CPU by any measureable amount. We have similar code in our product to update the bitrate on a display... – selbie Jan 05 '18 at 23:33
  • The thing is that I need it to be battery-efficient, since it is a constant background task that it is being updated – Nevaran Jan 06 '18 at 10:47

1 Answers1

0

I coded the following solution based on the accepted answer of this question:

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;
}

Even if it concerns file volumes, the underlying logic is almost the same. I limited the maximum magnitude to Mb since this is what your method is doing. I didn't change your implementation logics since you should know how and when to use the method much better than me.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • After some tests in different orders with a million for loop cycles, your code seems to be much slower(570ms) vs the one I have wrote at first (110-120). It might have something to do with `Math.Pow` maybe? – Nevaran Jan 06 '18 at 11:08