计算cpp程序运行时间
需要c++11支持
#include <chrono>
auto start = std::chrono::system_clock::now();
//do something
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << elapsed.count() <<"ms" << '\n';
#include <time.h>
time_t begin_t = clock();
// to do
time_t finish_t = clock();
cout<<"it cost " << (double )(finish_t - begin_t )/CLOCKS_PER_SEC <<" s"<<endl;
准确获取多线程序运行时间
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;
}