计算接收/发送数据的时间以计算带宽

时间:2013-11-29 16:04:24

标签: c time network-programming packet bandwidth

我有一个数据包嗅探器(见下文)。为了测量带宽,我认为我需要在接收数据的开始时启动计时器。记录已传输的字节数,然后计算平均带宽。为了测量接收/发送数据的时间,我做了:

int main() {
    //usual packet sniffer staff up untill while loop
    struct pcap_pkthdr header;
    const unsigned char *packet;
    char errbuf[PCAP_ERRBUF_SIZE];

    char *device;
    pcap_t *pcap_handle;

    int i;
    device = pcap_lookupdev(errbuf);
    if (device == NULL) perror("pcap_lookupdev failed");

    printf("Sniffing on device %s\n", device);

    pcap_handle = pcap_open_live(device, 4096, 1, 0, errbuf);
    if (pcap_handle == NULL) perror("pcap_open_live failed");   

    while (1) {
            //starting the timer
        double diff = 0.0;
        time_t start;
        time_t stop;
        char buff[128];
        time(&start);

            //receiving packet
        packet = pcap_next(pcap_handle, &header);

            //stopping the timer
        time(&stop);

             //measuring time of receiving data
        diff = difftime(stop, start);

        process_packet(packet, header.len, diff);
    }

}

diff总是为0.0000,这可能是错误的。我的理解是否正确,如果是,代码是否有任何问题?

我也尝试使用毫秒:

float diff;
clock_t start;
clock_t stop;
char buff[128];
start = clock();   

packet = pcap_next(pcap_handle, &header);//just creates a pointer in no time

stop = clock();
diff = (((float)stop - (float)start) / 1000000.0F ) * 1000;  

相同的输出......

1 个答案:

答案 0 :(得分:0)

样本数量不足或时钟太粗。

启动和停止之间的数据包数量可能太小。 time_t通常只有1秒的分辨率。 clock_t具有实现定义的CLOCKS_PER_SEC每秒滴答数。我已经看到18.2或100或1000等值。它也可能不足以容纳1个数据包。

建议将传输的字节时间增加到时钟周期的至少10倍。因此,如果您使用time_t并以19,200波特率运行,则传输192,000个字节。

为了保持一致性,同步开始时间会有所帮助。以下示例适用于clock_t,只是相应缩放。

// sync
time_t was;
time(&was);
time_t now;
do {
  time(&now);
} while (now == was);

// do test
do_test();  // about 10 seconds;

// results
time_t later;
time(&later);
time_t delta = late - now;
BitsPerDataByte = 1+8+1;
double TestedBaud = 1.0*DataBytesSent*BitsPerDataByte/delta;