0

C プログラムで clock_t の「秒」を for ループ カウンターとして使用しようとしています。それはどのように可能ですか?以下は、機能していない私のコーディングです。

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

int main()
{
  clock_t begin, end;
double time_spent;

begin = clock();
time_spent = (double)begin / CLOCKS_PER_SEC;

for(time_spent=0.0; time_spent<62000.0; time_spent++)
{
    printf("hello \n");

    if(time_spent==5.0)
    break;
}

end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

    printf(" %lf\n", time_spent);
}
4

1 に答える 1

2

あなたが何をしたいのかを正確に伝えるのは難しいです(あなたの質問に対するコメントによる)が、私はそれがこのようなものだと推測しています(ループは5秒後に終了します)。clock() は多少システムに依存することに注意してください。ウォールクロック時間の場合もありますが、CPU 時間であるはずです。

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

int main()
    {
    clock_t begin;
    double time_spent;
    unsigned int i;

    /* Mark beginning time */
    begin = clock();
    for (i=0;1;i++)
        {
        printf("hello\n");
        /* Get CPU time since loop started */
        time_spent = (double)(clock() - begin) / CLOCKS_PER_SEC;
        if (time_spent>=5.0)
            break;
        }
    /* i could conceivably overflow */
    printf("Number of iterations completed in 5 CPU(?) seconds = %d.\n",i);
    return(0);
    }
于 2013-09-30T03:07:06.173 に答える