Guide

タイムスタンプの精度レベル: 秒、ミリ秒、マイクロ秒、ナノ秒の説明

タイムスタンプの精度について

タイムスタンプの精度は、タイムスタンプが時間を測定する詳細レベルを指します。アプリケーションが異なれば、基本的な第 2 レベルの精度から超高精度のナノ秒測定まで、異なるレベルの精度が必要になります。これらの精度レベルを理解することは、ユースケースに適した形式を選択するために重要です。

主な精度レベルは次の 4 つです。

  1. (10 桁) - 標準 Unix タイムスタンプ
  2. ミリ秒 (13 桁) - JavaScript、Java のデフォルト
  3. マイクロ秒 (16 桁) - 高精度システム
  4. ナノ秒 (19 桁) - 超高精度のタイミング

4 つの精度レベル

1. 秒 (10 桁)

標準 Unix タイムスタンプ - オリジナルで最も一般的な形式。

形式

Example: 1704067200
Represents: January 1, 2024, 00:00:00 UTC
Precision: 1 second
Digit Count: 10 digits

特性

  • 範囲: 1901 年 12 月 13 日から 2038 年 1 月 19 日まで (32 ビット署名)
  • 範囲: 1677 年 9 月 21 日から 292,277,026,596 年 12 月 4 日まで (64 ビット署名)
  • ストレージ: 4 バイト (32 ビット) または 8 バイト (64 ビット)
  • 精度: ±0.5秒

いつ使用するか

  • イベントログ (ユーザー登録、ログイン時間)
  • データベースのタイムスタンプ (created_at、updated_at)
  • ファイルの変更時間
  • タスクのスケジュール設定 (cron ジョブ、バッチ プロセス)
  • 一般的なタイムスタンプ (秒未満の精度は必要ありません)

コード例

C/C++

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

int main() {
    time_t timestamp = time(NULL);
    printf("Current timestamp: %ld\n", timestamp);
    // Output: 1704067200 (10 digits)
    return 0;
}

パイソン

import time

timestamp = int(time.time())
print(f"Current timestamp: {timestamp}")
# Output: 1704067200 (10 digits)

PHP

<?php
$timestamp = time();
echo "Current timestamp: $timestamp\n";
// Output: 1704067200 (10 digits)
?>

SQL

-- Most databases store TIMESTAMP with second precision
SELECT UNIX_TIMESTAMP();
-- Output: 1704067200

2. ミリ秒 (13 桁)

JavaScript/Java 標準 - ミリ秒の精度のために小数点以下 3 桁を追加します。

形式

Example: 1704067200000
Represents: January 1, 2024, 00:00:00.000 UTC
Precision: 0.001 seconds (1 millisecond)
Digit Count: 13 digits

特性

  • 範囲: エポックから±8,640,000,000,000,000ミリ秒
  • ストレージ: 8バイト (64ビット整数または倍精度)
  • 精度: ±0.0005 秒 (0.5 ミリ秒)
  • 解像度: 1/1,000秒

いつ使用するか

  • Web アプリケーション (JavaScript Date.now())
  • パフォーマンス監視 (API 応答時間)
  • アニメーションのタイミング (フレーム レート、トランジション)
  • イベント追跡 (クリック回数、ユーザー インタラクション)
  • 取引システム (株価、注文執行)
  • リアルタイム通信 (チャット アプリケーション)

コード例

JavaScript

// Get current timestamp in milliseconds
const timestamp = Date.now();
console.log(timestamp);
// Output: 1704067200000 (13 digits)

// Create Date from millisecond timestamp
const date = new Date(1704067200000);
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z

ジャワ

// Get current timestamp in milliseconds
long timestamp = System.currentTimeMillis();
System.out.println(timestamp);
// Output: 1704067200000 (13 digits)

// Create Date from millisecond timestamp
Date date = new Date(1704067200000L);
System.out.println(date);

パイソン

import time

# Get timestamp in milliseconds
timestamp_ms = int(time.time() * 1000)
print(f"Millisecond timestamp: {timestamp_ms}")
# Output: 1704067200000 (13 digits)

Node.js

// High-resolution time in milliseconds
const start = performance.now();
// ... some operation ...
const end = performance.now();
console.log(`Operation took ${end - start} milliseconds`);

3. マイクロ秒 (16 桁)

高精度システム - マイクロ秒の精度で小数点以下 6 桁。

形式

Example: 1704067200000000
Represents: January 1, 2024, 00:00:00.000000 UTC
Precision: 0.000001 seconds (1 microsecond)
Digit Count: 16 digits

特性

  • 範囲: 非常に広い (紀元から±292,471年)
  • ストレージ: 8バイト(64ビット整数)
  • 精度: ±0.0000005 秒 (0.5 マイクロ秒)
  • 解像度: 1/1,000,000 秒

いつ使用するか

  • データベース システム (PostgreSQL、MongoDB)
  • 科学コンピューティング (物理シミュレーション)
  • ネットワーク プロトコル (パケットのタイムスタンプ)
  • オーディオ/ビデオ処理 (フレーム同期)
  • 高頻度取引 (マイクロ秒レベルの執行)
  • 分散システム (イベントの順序付け、因果関係)

コード例

パイソン

import time

# Get timestamp in microseconds
timestamp_us = int(time.time() * 1_000_000)
print(f"Microsecond timestamp: {timestamp_us}")
# Output: 1704067200000000 (16 digits)

# Using datetime
from datetime import datetime
dt = datetime.now()
timestamp_us = int(dt.timestamp() * 1_000_000)
print(f"Microsecond timestamp: {timestamp_us}")

行く

package main

import (
    "fmt"
    "time"
)

func main() {
    // Get current timestamp in microseconds
    timestamp := time.Now().UnixMicro()
    fmt.Printf("Microsecond timestamp: %d\n", timestamp)
    // Output: 1704067200000000 (16 digits)
}

PostgreSQL

-- PostgreSQL stores timestamps with microsecond precision
SELECT EXTRACT(EPOCH FROM NOW()) * 1000000;
-- Output: 1704067200000000

-- Create timestamp with microsecond precision
SELECT to_timestamp(1704067200.123456);
-- Output: 2024-01-01 00:00:00.123456+00

C++

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;

    // Get microsecond timestamp
    auto now = system_clock::now();
    auto micros = duration_cast<microseconds>(
        now.time_since_epoch()
    ).count();

    std::cout << "Microsecond timestamp: " << micros << std::endl;
    // Output: 1704067200000000 (16 digits)
    return 0;
}

4. ナノ秒 (19 桁)

超高精度タイミング - 小数点以下 9 桁のナノ秒精度。

形式

Example: 1704067200000000000
Represents: January 1, 2024, 00:00:00.000000000 UTC
Precision: 0.000000001 seconds (1 nanosecond)
Digit Count: 19 digits

特性

  • 範囲: エポックから ±292 年 (64 ビット符号付き)
  • ストレージ: 8バイト(64ビット整数)
  • 精度: ±0.0000000005 秒 (0.5 ナノ秒)
  • 解像度: 1/1,000,000,000秒

いつ使用するか

  • パフォーマンスプロファイリング (CPU サイクル測定)
  • ハードウェア計測 (オシロスコープ、ロジック アナライザー)
  • カーネル開発 (スケジューラーのタイムスタンプ)
  • リアルタイム システム (ロボット工学、航空宇宙)
  • 暗号化タイムスタンプ (ブロックチェーン、セキュリティ)
  • 物理実験 (粒子検出)

コード例

行く

package main

import (
    "fmt"
    "time"
)

func main() {
    // Get current timestamp in nanoseconds
    timestamp := time.Now().UnixNano()
    fmt.Printf("Nanosecond timestamp: %d\n", timestamp)
    // Output: 1704067200000000000 (19 digits)

    // Benchmark operations
    start := time.Now()
    // ... some operation ...
    elapsed := time.Since(start).Nanoseconds()
    fmt.Printf("Operation took %d nanoseconds\n", elapsed)
}

さび

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    // Get nanosecond timestamp
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap();

    let nanos = duration.as_nanos();
    println!("Nanosecond timestamp: {}", nanos);
    // Output: 1704067200000000000 (19 digits)
}

C++

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;

    // Get nanosecond timestamp
    auto now = system_clock::now();
    auto nanos = duration_cast<nanoseconds>(
        now.time_since_epoch()
    ).count();

    std::cout << "Nanosecond timestamp: " << nanos << std::endl;
    // Output: 1704067200000000000 (19 digits)
    return 0;
}

Linux (C)

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

int main() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    long long nanos = (long long)ts.tv_sec * 1000000000LL + ts.tv_nsec;
    printf("Nanosecond timestamp: %lld\n", nanos);
    // Output: 1704067200000000000 (19 digits)
    return 0;
}

精度比較表

レベル精度数字使用例言語/システム
2 番目1秒101704067200ログ、データベース、スケジュールC、PHP、Python、SQL
ミリ秒1ms (10⁻³s)131704067200000Web アプリ、取引、APIJavaScript、Java
マイクロ秒1μs (10⁻⁶s)161704067200000000HFT、オーディオ/ビデオ、ネットワークPython、Go、PostgreSQL
ナノ秒1ns (10⁻⁹s)191704067200000000000プロファイリング、ハードウェア、暗号Go、Rust、C++

精度レベル間の変換

スケールアップ (精度の追加)

// Second to Millisecond
const seconds = 1704067200;
const milliseconds = seconds * 1000;
// 1704067200000

// Millisecond to Microsecond
const microseconds = milliseconds * 1000;
// 1704067200000000

// Microsecond to Nanosecond
const nanoseconds = microseconds * 1000;
// 1704067200000000000

スケールダウン (精度の低下)

// Nanosecond to Microsecond
const nanos = 1704067200123456789;
const micros = Math.floor(nanos / 1000);
// 1704067200123456

// Microsecond to Millisecond
const millis = Math.floor(micros / 1000);
// 1704067200123

// Millisecond to Second
const secs = Math.floor(millis / 1000);
// 1704067200

Python 変換ユーティリティ

class TimestampConverter:
    """Convert between different timestamp precision levels"""

    @staticmethod
    def to_milliseconds(timestamp, from_precision='seconds'):
        """Convert any precision to milliseconds"""
        multipliers = {
            'seconds': 1000,
            'milliseconds': 1,
            'microseconds': 0.001,
            'nanoseconds': 0.000001
        }
        return int(timestamp * multipliers[from_precision])

    @staticmethod
    def to_microseconds(timestamp, from_precision='seconds'):
        """Convert any precision to microseconds"""
        multipliers = {
            'seconds': 1_000_000,
            'milliseconds': 1000,
            'microseconds': 1,
            'nanoseconds': 0.001
        }
        return int(timestamp * multipliers[from_precision])

    @staticmethod
    def to_nanoseconds(timestamp, from_precision='seconds'):
        """Convert any precision to nanoseconds"""
        multipliers = {
            'seconds': 1_000_000_000,
            'milliseconds': 1_000_000,
            'microseconds': 1000,
            'nanoseconds': 1
        }
        return int(timestamp * multipliers[from_precision])

# Usage
converter = TimestampConverter()

# Convert 1704067200 seconds to milliseconds
ms = converter.to_milliseconds(1704067200, 'seconds')
print(ms)  # 1704067200000

パフォーマンスに関する考慮事項

ストレージ要件

精度32ビット64ビットデータベースストレージ
4バイト8バイトタイムスタンプ (4 ~ 8 バイト)
ミリ秒❌ オーバーフロー8バイトBIGINT (8 バイト)
マイクロ秒❌ オーバーフロー8バイトBIGINT (8 バイト)
ナノ秒❌ オーバーフロー8バイトBIGINT (8 バイト)

処理速度

// Benchmark: Different precision levels
const iterations = 1000000;

// Seconds (fastest)
console.time('Seconds');
for (let i = 0; i < iterations; i++) {
    const ts = Math.floor(Date.now() / 1000);
}
console.timeEnd('Seconds');
// ~10ms

// Milliseconds (fast)
console.time('Milliseconds');
for (let i = 0; i < iterations; i++) {
    const ts = Date.now();
}
console.timeEnd('Milliseconds');
// ~12ms

// Microseconds (slower)
console.time('Microseconds');
for (let i = 0; i < iterations; i++) {
    const ts = performance.now() * 1000;
}
console.timeEnd('Microseconds');
// ~25ms

メモリへの影響

import sys

# Storage comparison
second_ts = 1704067200
millisecond_ts = 1704067200000
microsecond_ts = 1704067200000000
nanosecond_ts = 1704067200000000000

print(f"Second: {sys.getsizeof(second_ts)} bytes")      # 28 bytes
print(f"Millisecond: {sys.getsizeof(millisecond_ts)} bytes") # 28 bytes
print(f"Microsecond: {sys.getsizeof(microsecond_ts)} bytes") # 28 bytes
print(f"Nanosecond: {sys.getsizeof(nanosecond_ts)} bytes")  # 32 bytes

# In arrays/databases, smaller integers = better performance

精度と精度

違いを理解する

  • 精度: どれだけ細かく測定できるか (桁数)
  • 精度: 測定値が真の値にどれだけ近いか
Example:
Precision: Nanosecond timestamp (19 digits)
Accuracy: System clock may only be accurate to ±50ms

Result: High precision, low accuracy

システムクロックの制限

システム一般的な解像度精度
ウィンドウズ15.6ミリ秒±10-50ms
リナックス1μs~1ms±1-10ms
macOS1μs±1-10ms
リアルタイムOS1ns~1μs±1μs

システムの解像度をテストする

import time

def measure_clock_resolution():
    """Measure actual system clock resolution"""
    samples = []
    prev = time.time()

    for _ in range(100000):
        current = time.time()
        if current != prev:
            samples.append(current - prev)
            prev = current

    if samples:
        min_diff = min(samples)
        print(f"Minimum time difference: {min_diff * 1000:.6f}ms")
        print(f"Approximate resolution: {min_diff * 1_000_000:.2f}μs")

measure_clock_resolution()

ベストプラクティス

1. 適切な精度を選択する

# ✅ GOOD: Match precision to use case
user_login_time = int(time.time())  # Seconds are enough

# ❌ BAD: Unnecessary precision
user_login_time = int(time.time() * 1_000_000_000)  # Overkill!

2. 一貫して保存する

-- ✅ GOOD: Consistent precision across table
CREATE TABLE events (
    id BIGINT PRIMARY KEY,
    created_at BIGINT,      -- All in milliseconds
    updated_at BIGINT       -- All in milliseconds
);

-- ❌ BAD: Mixed precision
CREATE TABLE events (
    id BIGINT PRIMARY KEY,
    created_at INT,         -- Seconds
    updated_at BIGINT       -- Milliseconds (inconsistent!)
);

3. 選択を文書化する

/**
 * Timestamp precision: Milliseconds (13 digits)
 * Format: Unix timestamp * 1000
 * Example: 1704067200000 = Jan 1, 2024 00:00:00.000 UTC
 */
const timestamp = Date.now();

4. 変換は慎重に処理してください

# ✅ GOOD: Explicit conversion
def seconds_to_milliseconds(seconds):
    """Convert seconds to milliseconds"""
    return int(seconds * 1000)

# ❌ BAD: Implicit/unclear
def convert(ts):
    return ts * 1000  # What precision is this?

5. 精度の検証

function validateTimestamp(timestamp, expectedPrecision) {
    const digitCount = timestamp.toString().length;

    const expectedDigits = {
        'seconds': 10,
        'milliseconds': 13,
        'microseconds': 16,
        'nanoseconds': 19
    };

    if (digitCount !== expectedDigits[expectedPrecision]) {
        throw new Error(
            `Invalid ${expectedPrecision} timestamp: expected ${expectedDigits[expectedPrecision]} digits, got ${digitCount}`
        );
    }

    return true;
}

// Usage
validateTimestamp(1704067200000, 'milliseconds');  // ✅ Pass
validateTimestamp(1704067200, 'milliseconds');     // ❌ Error

よくある落とし穴

1. 浮動小数点の精度の損失

// ❌ BAD: JavaScript Number precision limit
const nanos = 1704067200123456789;  // 19 digits
console.log(nanos);
// Output: 1704067200123456800 (last digits lost!)

// ✅ GOOD: Use BigInt for nanoseconds
const nanos = 1704067200123456789n;
console.log(nanos.toString());
// Output: 1704067200123456789 (exact)

2. タイムゾーンの混乱

# ❌ BAD: Local time affects precision
import datetime
local_time = datetime.datetime.now()  # Includes local timezone
timestamp = local_time.timestamp()

# ✅ GOOD: Always use UTC
utc_time = datetime.datetime.utcnow()
timestamp = utc_time.timestamp()

3. オーバーフローの問題

c
// ❌ BAD: 32-bit overflow with milliseconds
int32_t timestamp_ms = time(NULL) * 1000;  // Overflow!

// ✅ GOOD: Use 64-bit for higher precision
int64_t timestamp_ms = (int64_t)time(NULL) * 1000;

関連ツール

無料のツールを使用して、さまざまなタイムスタンプ精度を処理します。

結論

タイムスタンプの精度レベルを理解することは、最新のソフトウェア開発にとって不可欠です。特定の要件に基づいて適切な精度レベルを選択してください。

  • : 汎用タイムスタンプ、ログ、データベース
  • ミリ秒: Web アプリケーション、API、リアルタイム機能
  • マイクロ秒: 高頻度取引、科学計算
  • ナノ秒: パフォーマンス プロファイリング、ハードウェア計測

覚えておいてください:

  • より高い精度 = より多くのストレージ + より多くの処理
  • 精度を実際のシステム精度に一致させる
  • アプリケーション全体で一貫性を保つ
  • 将来の開発者のために選択を文書化します

最終更新日: 2025 年 1 月