2016-06-14 40 views
1

我想要延遲爲500毫秒使用clock_t表示類型。例如我已經下面的代碼我的程序:時鐘函數usleep在c程序中不能正常工作?

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

int main() 
{ 
    clock_t start_t, end_t, total_t,start_2,end_2,total_2; 
    int i; 

    start_t = clock(); 
    printf("start_t = %ld\n", start_t); 

    //do a loop 
    for(i=0; i< 10000000; i++) 
    { 
    } 

    end_t = clock(); 


    printf("end_t = %ld \n", end_t); 

    total_t = (double)(end_t - start_t)*1000/CLOCKS_PER_SEC; 
    printf("Total1 in msec %ld \n",total_t); 



    start_2=clock(); 
    printf("start_2 %ld\n ", start_2); 
    usleep(500000); 

    end_2=clock(); 
    printf("end_2 %ld\n ", end_2); 
    total_2=(double)(start_2-end_2)*1000/CLOCKS_PER_SEC; 
    printf("Total2 in msec %ld\n ", total_2); 


    return(0); 
} 

我們發現,需要usleep微秒的值作爲輸入。所以我把500000

,但我得到:

start_t = 1041 
end_t = 50441 
Total1 in msec 49 

start_2 50446 
end_2 50478 
Total2 in msec 0 

錯在何處?爲什麼總數2 = 0?請幫忙嗎?

+2

*「時鐘()函數確定的處理器時間的使用量。」 *當你睡覺,久而久之,但沒有使用的處理器時間。 – user3386109

+0

那麼我需要delay()函數嗎? –

+0

不,您需要使用不同的功能來測量牆面時間。在MAC上,使用'mach_absolute_time'。在Windows上,它是'QueryPerformanceCounter'。 – user3386109

回答

0

找到了解決方案。我寫了一個延時功能:

void delay (unsigned int msecs) { 
clock_t goal = msecs*CLOCKS_PER_SEC/1000 + clock(); //convert msecs to clock count 
while (goal > clock());    // Loop until it arrives. 

}

0

實際上,時鐘函數記錄了這個過程的cpu週期數。當你調用usleep函數時,cpu不會爲這個過程提供任何時間幻燈片。 所以真正的原因是clock()函數。也許你可以找到一些功能來獲得系統時間。我認爲它會起作用。