15

経過時間に関するこの記事を読んだ後、ループの実行時間を計算する簡単なコードを作成しました。

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

int main (int argc, char** argv) {
    struct timeval, tvalBefore, tvalAfter;

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 1000) {
        i ++;
    }

    gettimeofday (&tvalAfter, NULL);

    printf("Time in microseconds: %0.3f microseconds\n",
            (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) 
          )
    return 0;
}

clangコンパイラは私に次のエラーを出します:

print_time.c:7:16: error: expected identifier or '('
        struct timeval, *tvalBefore, *tvalAfter;
                      ^
print_time.c:13:17: error: use of undeclared identifier 'tvalBefore'
        gettimeofday (&tvalBefore, NULL);
                       ^
print_time.c:19:17: error: use of undeclared identifier 'tvalAfter'
        gettimeofday (&tvalAfter, NULL);
                       ^
print_time.c:22:12: error: use of undeclared identifier 'tvalAfter'
                        (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) 
                                ^
print_time.c:22:31: error: use of undeclared identifier 'tvalBefore'
                        (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) 
                                                   ^
5 errors generated.

私のコードの何が問題なのか理解できません、何か考えはありますか?

4

2 に答える 2

36

コードに 2 つの入力エラーがあります。

 struct timeval,

する必要があります

 struct timeval

括弧の後にはprintf()セミコロンが必要です。

また、コンパイラによっては、非常に単純なサイクルが最適化されるだけで、何をしても 0 マイクロ秒の時間が得られる場合があります。

最後に、時間の計算が間違っています。マイクロ秒を無視して、秒のみを考慮します。秒の差を取得し、100 万を掛けてから、「after」tv_usecを加算して「before」を減算する必要がありtv_usecます。整数の秒数を float にキャストしても、何も得られません。

のマニュアルページをチェックすることをお勧めしますstruct timeval

これはコードです:

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

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;
    }

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;
}
于 2012-10-04T08:12:13.880 に答える
13

変化する:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

に:

struct timeval tvalBefore, tvalAfter;

行ごとに単一の宣言がある場合、この間違いを犯す可能性は低くなります (IMO):

struct timeval tvalBefore;
struct timeval tvalAfter;

1 行で型へのポインターを宣言すると、エラーが発生しやすくなります。

struct timeval* tvalBefore, tvalAfter;

tvalBeforeはですstruct timeval*tvalAfterstruct timevalです。

于 2012-10-04T08:11:00.770 に答える