服务器定时响应时间

Timing response time from server

我正在开发一个向服务器发送消息的 UDP 客户端。我还需要以微秒为单位计算 RTT(往返时间)。我有两个变量 (t1, t2),我想将这些时间存储在其中。t1 在消息发送到服务器时使用,而 t2 在客户端收到消息后立即使用。然后我想调用一个像 difftime(t1,t2); 这样的函数来显示这个时差。我有 #include <time.h> 作为预处理器,但我不知道应该为 t1 和 t2 使用什么数据类型。在谷歌搜索 time.h 手册页中,我看到了一些看起来像称为 suseconds_t 的数据类型(如果我理解正确的话,它类似于使用 time_t),但我不确定如何使用它。任何帮助将不胜感激!

为此您可以使用 struct timevalgettimeofday()

struct timeval t1, t2;

gettimeofday(&t1, NULL);
// send packet and receive response
gettimeofday(&t2, NULL);

然后你可以使用这样的函数来计算差值:

struct timeval diff_timeval(struct timeval t2, struct timeval t1)
{
    struct timeval result;

    result.tv_sec = t2.tv_sec - t1.tv_sec;      // subtract seconds
    result.tv_usec = t2.tv_usec - t1.tv_usec;   // subtract microseconds
    // microsecond result could be negative, ex. 2.1 - 1.9 = 1 sec - 800000 microseconds
    // if so, subtract one second and add 1000000 microseconds
    while (result.tv_usec < 0) {
        result.tv_usec += 1000000;
        result.tv_sec--;
    }
    return result;
}