time.h clock() broken on OS X?

帅比萌擦擦* 提交于 2019-12-11 10:37:33

问题


Am I going mad? I'm running this on x86_64.

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    printf("Clock: %f\n", clock() / (double)CLOCKS_PER_SEC);
    sleep(1);
    printf("Clock: %f\n", clock() / (double)CLOCKS_PER_SEC);
    sleep(1);
    printf("Clock: %f\n", clock() / (double)CLOCKS_PER_SEC);
    return 0;
}

This prints

Clock: 0.002880
Clock: 0.002968
Clock: 0.003019

It clearly waits for a second at the sleep(1) lines, but the output is clearly wrong.

If that doesn't work, is there a portable C alternative?


回答1:


I'm an idiot. clock() returns processor time used.




回答2:


You can declare an variable time_t t1,t2; t1 = time(NULL); sleep(1); t2 = time(NULL); You can debug and view the values of t1 and t2. I think you can take an reference from http://www.cplusplus.com/reference/clibrary/ctime/time/



来源:https://stackoverflow.com/questions/13510758/time-h-clock-broken-on-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!