Table of Contents

1 C99 get current time

  • Get current time in secnod and nanosecond

    // FILE: /Users/aaa/myfile/github/c99/elapsedtime.c
    #include <stdio.h>
    #include <unistd.h>  // usleep()
    #include <time.h>
    
    // KEY: get time, get nano second, get nanosecond
    int main() {
        long nano = 1E9;
        struct timespec start_time, end_time;
    
        // Get the start time
        clock_gettime(CLOCK_REALTIME, &start_time);
    
        usleep(1000);
    
        // Get the end time
        clock_gettime(CLOCK_REALTIME, &end_time);
    
        printf("start_time.tv_sec  %09ld\n", start_time.tv_sec);
        printf("start_time.tv_nsec %09ld\n", start_time.tv_nsec);
        printf("end_time.tv_sec  %09ld\n", end_time.tv_sec);
        printf("end_time.tv_nsec %09ld\n", end_time.tv_nsec);
    
        // Calculate the elapsed time
        long seconds = end_time.tv_sec - start_time.tv_sec;
        long nanoseconds = end_time.tv_nsec - start_time.tv_nsec;
    
        // Print the elapsed time
        printf("Elapsed time: %ld %09ld seconds\n", seconds, nanoseconds);
        printf("Elapsed time: %ld %09f seconds\n", seconds, (double)nanoseconds/nano);
        return 0;
    }
    

2 C99 get time function

  • time function from $g/c99lib/AronCLibNew.h

    uint64_t time_second(){
      struct timeval tv;
      gettimeofday(&tv, NULL);
      return (uint64_t)tv.tv_sec;
    }
    
    uint64_t time_micro() {
      struct timeval tv;
      uint64_t micro = 1E6;
      gettimeofday(&tv, NULL);
      return ((uint64_t)tv.tv_sec * micro) + ((uint64_t)tv.tv_usec);
    }
    
    uint64_t time_nano() {
      struct timeval tv;
      uint64_t nano = 1E9;
      gettimeofday(&tv, NULL);
      return ((uint64_t)tv.tv_sec * nano) + ((uint64_t)tv.tv_usec * 1000);
    }
    

3 C99 get second and nanosecond

  • timespec

    struct timespec {
      time_t tv_sec;   // seconds
      long   tv_nsec;  // nanoseconds
    };
    

4 C99 get second and microsecond

  • See timeval

    struct timeval {
      time_t      tv_sec;     // seconds
      suseconds_t tv_usec;    // microseconds
    };
    
    • tv_sec Represents the number of whole seconds since the epoch (00:00:00) Coordinated Universal Time(UTC),(January 1, 1970)
    • tv_usec Represents the number of microseconds remaining after tv_sec

5 Swift, Epoch time, time since 1970

#!/usr/bin/swift
import Foundation
import Swift

// Compile: swift timestamp.swift 
print("Get time since 1970")
let timestamp = NSDate().timeIntervalSince1970
let millisecond = timestamp * 1000000
print("millisecond => \(millisecond)")
print("second => \(Int(timestamp))")

Author: aaa

Created: 2024-07-14 Sun 11:22

Validate