c获取程序运行时间(纳米级)
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
static unsigned long GetTickCount(){
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (ts.tv_sec*1000000 + ts.tv_nsec / 1000);
}
int main(){
unsigned long t0 = GetTickCount();
// start do your thing
int i = 0;
for(i = 0 ; i < 10;i++){
printf("%d ", i);
}
printf("\n");
//end
unsigned long t1 = GetTickCount();
printf("Cost time:%ld us \n", t1 - t0);
return 0;
}
或者
#include <stdio.h>
#include <sys/time.h>
int main(){
struct timeval t_start,t_end;
long cost_time = 0;
//get start time
gettimeofday(&t_start, NULL);
printf("Start time: %ld us", t_start.tv_usec);
//do something
printf("-------------------\n");
//get end time
gettimeofday(&t_end, NULL);
printf("End time: %ld us\n", t_end.tv_usec);
//calculate time slot
cost_time = t_end.tv_usec - t_start.tv_usec;
printf("Cost time: %ld us", cost_time);
return 0;
}
static uint64_t GetTickCount() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}