Skip to content

Instantly share code, notes, and snippets.

@jemyzhang
Last active April 1, 2024 11:38
Show Gist options
  • Save jemyzhang/6897721 to your computer and use it in GitHub Desktop.
Save jemyzhang/6897721 to your computer and use it in GitHub Desktop.
common functions
/**
* Returns the current resident set size (physical memory use) measured
* in bytes, or zero if the value cannot be determined on this OS.
*/
size_t getCurrentRSS( )
{
long rss = 0L;
FILE* fp = NULL;
if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
return (size_t)0L; /* Can't open? */
if ( fscanf( fp, "%*s%ld", &rss ) != 1 )
{
fclose( fp );
return (size_t)0L; /* Can't read? */
}
fclose( fp );
return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE);
}
#include <stdarg.h>
#include <stdio.h>
#include <sys/time.h>
#define LOG_ERROR(fmt, arg...) \
log_print(LOG_LEVEL_ERROR, __FILE__, __FUNCTION__, __LINE__, fmt, ##arg)
static int gs_log_level = LOG_LEVEL_ERROR;
void log_print(int level, const char *file, const char *function, int line,
const char *fmt, ...) {
if (level <= gs_log_level) {
struct tm *tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
tm_info = localtime(&tv.tv_sec);
fprintf(stderr, "\x1b[37;44m[%04d-%02d-%02d %02d:%02d:%02d.%03ld]\x1b[0m ",
(1900 + tm_info->tm_year), tm_info->tm_mon, tm_info->tm_mday,
tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec,
tv.tv_usec / 1000);
fprintf(stderr, " [%s - %s:%d] ", file, function, line);
int size = 0;
char *p = NULL;
va_list ap;
va_start(ap, fmt);
size = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (size < 0)
return;
size++; /* For '\0' */
p = (char *)malloc(size);
if (p == NULL)
return;
va_start(ap, fmt);
size = vsnprintf(p, size, fmt, ap);
if (size < 0) {
free(p);
return;
}
va_end(ap);
fprintf(stderr, "%s", p);
free(p);
}
}
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#define gettid() syscall(__NR_gettid)
int main () {
printf("pid = %ld tid= %ld\n", getpid(), (long int)gettid());
return 0;
}
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
void my_backtrace() {
void *buffer[100] = {NULL};
char **trace = NULL;
int size = backtrace(buffer, 100);
trace = backtrace_symbols(buffer, size);
if (NULL == trace) {
return;
}
printf("----------backtrace----------\n");
for (int i = 0; i < size; ++i) {
printf("%s\n", trace[i]);
}
free(trace);
printf("----------done----------\n");
}
unsigned int systime(void)
{
struct timeval tm;
gettimeofday(&tm,NULL);
return tm.tv_sec*1000 + tm.tv_usec/1000;
}
#include <sys/time.h>
struct timeval tmsStart, tmsEnd;
gettimeofday(&tmsStart, 0);
//TODO: do some job
gettimeofday(&tmsEnd, 0);
int timediff = 1000 * (tmsEnd.tv_sec - tmsStart.tv_sec) + (tmsEnd.tv_usec - tmsStart.tv_usec) / 1000;
printf("time over %dms\n", timediff);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment