C 定时器差值返回 0ms

C Timer Difference returning 0ms

我正在学习 C(和 Cygwin)并尝试完成一个简单的远程执行系统以完成作业。

我被挂断的一个简单要求是:'Client will report the time taken for the server to respond to each query.'

我尝试四处搜索并实施其他可行的解决方案,但结果总是返回 0。

我所拥有的片段:

#include <time.h>

for(;;)
{
    //- Reset loop variables
    bzero(sendline, 1024);
    bzero(recvline, 1024);
    printf("> ");
    fgets(sendline, 1024, stdin);

    //- Handle program 'quit'
    sendline[strcspn(sendline, "\n")] = 0;
    if (strcmp(sendline,"quit") == 0) break;

    //- Process & time command
    clock_t start = clock(), diff;
    write(sock, sendline, strlen(sendline)+1);
    read(sock, recvline, 1024);
    sleep(2);
    diff = clock() - start;
    int msec = diff * 1000 / CLOCKS_PER_SEC;

    printf("%s (%d s / %d ms)\n\n", recvline, msec/1000, msec%1000);
}

我也尝试过使用浮点数,而不是除以 1000,而是乘以 10,000 只是为了查看是否有值闪烁,但总是返回 0。 显然我的实现方式肯定有问题,但经过大量阅读后我无法弄清楚。

--编辑--

值的打印输出:

clock_t start = clock(), diff;
printf("Start time: %lld\n", (long long) start);
//process stuff
sleep(2);
printf("End time: %lld\n", (long long) clock());
diff = clock() - start;

printf("Diff time: %lld\n", (long long) diff);
printf("Clocks per sec: %d", CLOCKS_PER_SEC);

结果: 开始时间:15 结束时间:15 差异时间:0 每秒时钟数:1000

-- 最终工作代码 --

#include <sys/time.h>

//- Setup clock
struct timeval start, end;

//- Start timer
gettimeofday(&start, NULL);

//- Process command
/* Process stuff */

//- End timer
gettimeofday(&end, NULL);

//- Calculate differnce in microseconds
long int usec =
    (end.tv_sec * 1000000 + end.tv_usec) -
    (start.tv_sec * 1000000 + start.tv_usec);

//- Convert to milliseconds
double msec = (double)usec / 1000;

//- Print result (3 decimal places)
printf("\n%s (%.3fms)\n\n", recvline, msec);

我认为你误解了 clock()sleep()

clock 测量程序使用的 CPU 时间,但 sleep 将在不使用任何 CPU 时间的情况下休眠。也许您想改用 time()gettimeofday()

Cygwin 表示您在 Windows.

在Windows上,执行线程上的"current time"每64秒(大约16ms)才更新一次,所以如果clock()是基于它的,即使它returns 一个毫秒数,它永远不会比 15.6 毫秒更精确。

GetThreadTimes()有同样的限制。