C/C++下準確獲取多執行緒序執行時間
阿新 • • 發佈:2020-12-23
技術標籤:# C++
1、acl_meter_time.c
#include <lzma.h>
#include <zconf.h>
#include <pthread.h>
#include <malloc.h>
#include <sys/time.h>
static void free_tls(void *ptr)
{
free(ptr);
}
static pthread_key_t once_key;
static void once_init(void){
pthread_key_create (&once_key, free_tls);
}
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
static void *tls_calloc(size_t len){
void *ptr;
pthread_once(&once_control, once_init);
ptr = pthread_getspecific(once_key);
if(ptr == NULL){
ptr = calloc(1, len);
pthread_setspecific (once_key, ptr);
}
return ptr;
}
typedef struct {
struct timeval stamp;
int init_done;
} METER_CTX_T;
double acl_meter_time(const char *filename, int line, const char *info){
struct timeval now;
double f;
METER_CTX_T *ctx = tls_calloc(sizeof(METER_CTX_T));
if(ctx- >init_done == 0){
ctx->init_done = 1;
gettimeofday(&ctx->stamp, NULL);
}
gettimeofday(&now, NULL);
now.tv_usec -= ctx->stamp.tv_usec;
if (now.tv_usec < 0) {
--now.tv_sec;
now.tv_usec += 1000000;
}
now.tv_sec -= ctx->stamp.tv_sec;
f = now.tv_sec * 1000.0 + now.tv_usec/1000.0;
if (info)
printf("tid=%lu, %s(%d), %s: time inter = %8.3f ms\r\n",
(unsigned long) pthread_self(), filename, line, info, f);
else
printf("tid=%lu, %s(%d): time inter = %8.3f ms\r\n",
(unsigned long) pthread_self(), filename, line, f);
gettimeofday(&ctx->stamp, NULL);
return (f);
}
2、acl_meter_time.h
#pragma once
double acl_meter_time(const char *filename, int line, const char *info);
#define ACL_METER_TIME(info) acl_meter_time(__FILE__, __LINE__, info)
3、如何使用
#include <stdio.h>
#include <sys/time.h>
#include <zconf.h>
#include <pthread.h>
#include "stdlib.h"
#include "acl_meter_time.h"
void *thr_fn1(void *arg)
{
ACL_METER_TIME(NULL);
usleep(1000);
ACL_METER_TIME(NULL);
printf("thread 1 returning\n");
return((void *)1);
}
int main(void)
{
ACL_METER_TIME(NULL);
int err;
pthread_t tid1, tid2;
void *tret;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != 0){
fprintf(stderr, "can't create thread 1");
exit(err);
}
err = pthread_join(tid1, &tret);
if (err != 0){
fprintf(stderr, "can't join with thread 1");
exit(err);
}
usleep(1000);
ACL_METER_TIME(NULL);
return 0;
}