User Tools

Site Tools


,

Simple pseudo-monotic id generator

genid.c
/*
 * Copyright 2023 Oleg Borodin  <borodin@unix7.org>
 */
 
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <stdio.h>
 
#ifdef __linux__
#include <endian.h>
#else
#include <sys/endian.h>
#endif
 
int64_t getid(void) {
    uint64_t id = 0;
 
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    uint64_t nsec = (uint64_t)(now.tv_sec * 1000000) + (uint64_t)now.tv_nsec;
 
    uint64_t r = (uint64_t)(rand() % 0xFFFF);
    id = (nsec << 16);
    id |= (r & (uint64_t)0xFFFF);
    id &= ~((uint64_t)1 << 63);
 
    return (int64_t)id;
}
 
 
int main(int argc, char **argv) {
    srand((unsigned)time(NULL));
 
    int64_t id = getid();
    printf("%lx %ld\n", id, id);
 
    return 0;
}
$ ./genid
733d02db7f3c132b 8303796429696799531