Last active
July 26, 2024 14:09
-
-
Save shawnfeng0/82b40ca33df87a7bb22eda31fe6f9d40 to your computer and use it in GitHub Desktop.
temp_file_write function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <pthread.h> | |
#include <sys/file.h> | |
#include <time.h> | |
static inline long long get_uptime_ms() { | |
struct timespec ts; | |
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { | |
perror("clock_gettime"); | |
return -1; | |
} | |
long long uptime_ms = ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL; | |
return uptime_ms; | |
} | |
static inline void temp_file_write(const char *path, const char* data, size_t length) { | |
static int fd = -1; | |
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; | |
pthread_mutex_lock(&mutex); | |
if (fd == -1) { | |
fd = open(path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); | |
} | |
write(fd, data, length); | |
pthread_mutex_unlock(&mutex); | |
} | |
#define LOG_PATH "test.log" | |
#define LOG_DEBUG(fmt, ...) { \ | |
char buf[2048]; \ | |
snprintf(buf, sizeof(buf), "%.3f " fmt "\n", get_uptime_ms()/1000.f, ##__VA_ARGS__); \ | |
temp_file_write(LOG_PATH, buf, strlen(buf)); \ | |
} | |
#define LOG_RAW(data, length) { \ | |
temp_file_write(LOG_PATH, data, length);\ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment