66

現在のタイムスタンプを取得し、を使用して印刷したいと思いfprintfます。

4

5 に答える 5

79

32ビットシステムの場合:

fprintf(stdout, "%u\n", (unsigned)time(NULL)); 

64ビットシステムの場合:

fprintf(stdout, "%lu\n", (unsigned long)time(NULL)); 
于 2012-08-01T18:32:57.957 に答える
40

によって返される値をキャストしているだけですtime()

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

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

あなたが欲しいもの?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

エポックからマイクロ秒を取得するには、C11以降、ポータブルな方法を使用します

int timespec_get(struct timespec *ts, int base)

残念ながら、C11はまだどこでも利用できるわけではないため、現時点では、ポータブルに最も近いのは、POSIX関数の1つclock_gettimeまたはgettimeofday(POSIX.1-2008で廃止とマークされているclock_gettime)を使用することです。

両方の関数のコードはほぼ同じです。

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

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}
于 2012-08-01T18:37:19.380 に答える
11

2番目の精度では、関数から取得した構造体tv_secのフィールドを印刷できます。例えば:timevalgettimeofday()

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

int main()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
    return 0;
}

コンパイルと実行の例:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

ただし、最近はエポックからしばらく経ちlong int、秒数を合わせるために使用されていることに注意してください。

人間が読める時間を印刷する機能もあります。詳細については、このマニュアルページを参照してください。以下を使用した例を示しctime()ます。

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

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}

実行と出力の例:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 
于 2012-08-01T18:32:38.510 に答える
4
#include <stdio.h>
#include <time.h>

int main ()
{
   time_t seconds;

   seconds = time(NULL);
   printf("Seconds since January 1, 1970 = %ld\n", seconds);

   return(0);
}

そして、同様の結果が得られます:
1970年1月1日からの秒数=1476107865

于 2016-10-10T14:02:10.960 に答える
1

重要な点は、2つのタイムスタンプの違いに基づいてタスクを実行するかどうかを検討することです。これは、を使用して生成すると、システムの時刻を設定する瞬間gettimeofday()でも、奇妙な動作が発生するためです。clock_gettime(CLOCK_REALTIME,..)

このような問題を防ぐために、clock_gettime(CLOCK_MONOTONIC_RAW, &tms)代わりに使用してください。

于 2020-09-03T08:19:25.060 に答える