I need to calculate the used bandwidth in a bus. All packets can be read for any client in the bus, then if I'm a only listener I can catch all packets and know how many bytes are moving in the bus. Then my first approach to calculate the used bandwidth is something like this:

1) unsigned long second[60] to store bytes on the second 0, 1, 2, 3

2) second[now] += readBytes;

3) then use last 3 seconds to calculate the bandwidth Ex: (second[now-2] + second[now-1] + second[now])/3 // Check that 0-2=58

4) Show every second the prev calc based on 1Mbps teoric bandwidth limit.

Is this the way ?


Code that I'm testing

unsigned last_second;
unsigned long second[60], packets_second[60];


            gettimeofday(&now, NULL);
            tm = localtime(&now.tv_sec);
            if (last_second != tm->tm_sec) {
                second[tm->tm_sec] = 0;
                packets_second[tm->tm_sec] = 0;
                printf("\rBandwidth: %.2f%% packets: %lu bits/s: %lu bytes/s: %lu              ", (second[last_second]*100.0/1000000.0), packets_second[last_second], second[last_second], second[last_second]/8);
                last_second = tm->tm_sec;


function Receive() {
        second[tm->tm_sec] += nBitsReceived; // Bits, bits, bits!
        last_second = tm->tm_sec;