这里就直接贴上代码了,获取某一段程序运行的时间。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <sys/time.h>
#include <unistd.h>
#define USDIFF(new, old) (1000000 * (int64_t)((new).tv_sec - (old).tv_sec) + (new).tv_usec - (old).tv_usec)
using namespace std;
int main(int argc, char *argv[]) {
int sleep_time = atoi(argv[1]);
struct timeval t1, t2;
gettimeofday(&t1, NULL);
sleep(sleep_time);
gettimeofday(&t2, NULL);
std::cout << "time diff: " << USDIFF(t2, t1)/1000.0 << std::endl;
return 0;
}