C입출력과 파일

time.h 기초

`time_t`로 에포크 시각을 얻고 `difftime`으로 경과 시간을 계산하는 방법, `clock_t`로 CPU 사용 시간을 측정하는 방법, `strftime`으로 날짜·시간을 포맷하는 방법을 정리합니다.

마지막 수정 2026년 3월 26일

기본 패턴

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

// 현재 시각 (유닉스 에포크 기준 초)
time_t now = time(NULL);
printf("epoch: %lld\n", (long long)now);

// 날짜/시간 포맷
char buf[64];
struct tm *t = localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);
printf("%s\n", buf);   // 예: 2026-03-26 14:30:00

설명

time_t — 에포크 기준 초 단위 시각

time(NULL)은 1970-01-01 00:00:00 UTC(유닉스 에포크)부터 현재까지의 초 수를 time_t로 반환합니다. 두 시각의 차이는 difftime으로 구합니다.

c
time_t start = time(NULL);

// ... 작업 수행 ...

time_t end = time(NULL);
double elapsed = difftime(end, start);
printf("경과 시간: %.0f초\n", elapsed);

// ❌ end - start 직접 빼기 — time_t가 정수 보장 없음
// ✅ difftime 사용 (double 반환)

struct tm — 날짜/시간 분해

localtimetime_t를 로컬 시간대의 struct tm으로 변환합니다. gmtime은 UTC 기준입니다.

c
time_t now = time(NULL);
struct tm *t = localtime(&now);

printf("연: %d\n",  t->tm_year + 1900);  // 1900년 기준 더함
printf("월: %d\n",  t->tm_mon  + 1);     // 0~11 → 1~12
printf("일: %d\n",  t->tm_mday);
printf("시: %d\n",  t->tm_hour);
printf("분: %d\n",  t->tm_min);
printf("초: %d\n",  t->tm_sec);
printf("요일: %d\n", t->tm_wday);  // 0=일요일

strftime — 날짜 포맷 출력

c
char buf[128];
time_t now = time(NULL);
struct tm *t = localtime(&now);

strftime(buf, sizeof(buf), "%Y-%m-%d",           t);  // 2026-03-26
strftime(buf, sizeof(buf), "%H:%M:%S",           t);  // 14:30:00
strftime(buf, sizeof(buf), "%Y/%m/%d %a",        t);  // 2026/03/26 Thu
strftime(buf, sizeof(buf), "%B %d, %Y",          t);  // March 26, 2026

주요 포맷 코드: %Y 4자리 연, %m 월(0112), %d 일, %H 시(0023), %M 분, %S 초, %a 요일 약어, %A 요일 전체.

clock_t — CPU 실행 시간 측정

clock()은 프로그램이 CPU를 실제로 사용한 시간을 반환합니다. sleep이나 I/O 대기 시간은 포함되지 않아 알고리즘 성능 측정에 적합합니다.

c
#include <time.h>

clock_t t1 = clock();

// CPU 집약적 작업
long sum = 0;
for (long i = 0; i < 100000000L; i++) sum += i;

clock_t t2 = clock();
double cpu_sec = (double)(t2 - t1) / CLOCKS_PER_SEC;
printf("CPU 시간: %.3f초\n", cpu_sec);
printf("sum = %ld\n", sum);

빠른 정리

목적적합한 선택
현재 시각 (에포크 초)time(NULL)
두 시각의 경과 시간difftime(end, start)
로컬 날짜/시간 분해localtime(&t)struct tm
UTC 날짜/시간 분해gmtime(&t)
날짜/시간 포맷 출력strftime(buf, size, fmt, tm)
CPU 사용 시간 측정clock() / CLOCKS_PER_SEC

주의할 점

localtimegmtime은 정적 버퍼를 반환해 스레드 안전하지 않습니다. 결과를 즉시 복사하거나 localtime_r/gmtime_r(POSIX)를 사용하세요.

c
// ❌ 같은 정적 버퍼를 재사용 — 두 번째 호출이 첫 번째를 덮어씀
struct tm *t1 = localtime(&time1);
struct tm *t2 = localtime(&time2);
// t1과 t2는 같은 포인터 — t1이 time2 값으로 덮어씌워짐

// ✅ 값 복사
struct tm local_t;
struct tm *tmp = localtime(&now);
local_t = *tmp;   // 복사

// ✅ POSIX: 스레드 안전 버전
struct tm result;
localtime_r(&now, &result);

tm_year는 1900년 기준, tm_mon은 0~11이므로 출력 시 각각 +1900, +1을 해야 합니다.

참고 링크

1 sources