统计函数执行时间(多线程环境下统计结果不准)
// 无返回值
#define FUNC_EXEC_TIME_NORET(fun,promote) ({ \
unsigned long long timeDelta = 0; \
struct timespec t1 = {0}; \
struct timespec t2 = {0}; \
clock_gettime(CLOCK_MONOTONIC, &t1); \
fun; \
clock_gettime(CLOCK_MONOTONIC, &t2); \
timeDelta = (unsigned long long)(t2.tv_sec1000 + t2.tv_nsec/1000000) - (unsigned long long)(t1.tv_sec1000 + t1.tv_nsec/1000000); \
printf(“%s %lld \n”, promote, timeDelta); \
})
// 有返回值
#define FUNC_EXEC_TIME_WITHRET(fun,promote,ret) ({ \
typeof(ret) status1; \
unsigned long long timeDelta = 0; \
struct timespec t1 = {0}; \
struct timespec t2 = {0}; \
clock_gettime(CLOCK_MONOTONIC, &t1); \
status1 = fun; \
clock_gettime(CLOCK_MONOTONIC, &t2); \
timeDelta = (unsigned long long)(t2.tv_sec1000 + t2.tv_nsec/1000000) - (unsigned long long)(t1.tv_sec1000 + t1.tv_nsec/1000000); \
printf(“%s %llu \n”, promote, timeDelta); \
status1; \
})
#define DEBUG_BUFFER_MAX_LENGTH (512)
/// 当前打印中增加线程号和时间戳打印
void PRINT_EX(const char* format, …)
{
char buffer[DEBUG_BUFFER_MAX_LENGTH]={0};
pid_t tid = 0;
tid = syscall(SYS_gettid);
unsigned long long jiffer = 0;
struct timeval val = {0};
gettimeofday(&val, NULL);
jiffer = (unsigned long long)val.tv_sec * 1000 + (unsigned long long)val.tv_usec / 1000;
va_list arg;
va_start (arg, format);
vsnprintf(buffer, DEBUG_BUFFER_MAX_LENGTH, format, arg);
va_end (arg);
printf( “tid:%d jiffer:%llu %s”, tid, jiffer, buffer);
}
宏测试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <syscall.h>
#include <stdarg.h>
void fun1(int a, int b)
{
int c = a + b;
sleep(3);
}
int fun2(int a, int b)
{
int c = a + b;
sleep(5);
return c;
}
void fun3()
{
sleep(2);
}
int main(int argc, char *argv[])
{
int ret = 0;
FUNC_EXEC_TIME_NORET(fun1(3,4),“fun1”);
ret = FUNC_EXEC_TIME_WITHRET(fun2(3,4),“fun2”,ret);
PRINT_EX(“fun3 start\n”);
fun3();
PRINT_EX(“fun3 end\n”);
}