在设计并实现算法时,往往需要对比下不同算法的运行耗时情况,本文记录了不同编程语言实现代码运行耗时检测的方式,不定时维护补充。
matlab代码耗时检测
模式:
tic
operations;%操作
toc
例:
tic
pause(0.5)
toc
输出:
时间已过 0.500878 秒。
C/C++代码耗时检测方法(windows)
C/C++语言中求程序执行的时间可以使用clock()函数实现。
NAME
clock - determine processor time //处理器时间处理
SYNOPSIS
#include <time.h>
clock_t clock(void);
DESCRIPTION
The clock() function returns an approximation of processor time used by the program.
RETURN VALUE
The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by
CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the
function returns the value (clock_t) -1.
返回值是clock_t类型的CPU 时间,除以CLOCKS_PER_SEC得到秒值
例:
#include <iostream>
#include <time.h>
#include <windows.h> // Windows系统下的头文件
int main()
{
clock_t time_start = clock();
Sleep(1001); // Windows系统下的延时函数,参数单位为ms (注意:S为大写)
clock_t time_end = clock();
std::cout << "Running Time (s): " << (1.0 * time_end - 1.0 * time_start) / (1.0 * CLOCKS_PER_SEC) << std::endl;
return 0;
}
输出:
C/C++代码耗时检测方法(ubuntu)
ubuntu下,有两种方法,一种使用gettimeofday函数实现,例程如下:
#include <iostream>
#include <vector>
#include <sys/time.h>
#include <unistd.h>
#define MILLION 1000000L
using namespace std;
int main(void)
{
uint32_t total_time;
struct timeval t_start;
if(gettimeofday(&t_start, NULL)){
cout<<"Failed to get start time"<<endl;
return -1;
}
/********* target task **************/
sleep(2);
/************************************/
struct timeval t_end;
if(gettimeofday(&t_end, NULL)){
cout<<"Failed to get end time"<<endl;
return -1;
}
total_time = MILLION*(t_end.tv_sec - t_start.tv_sec) + t_end.tv_usec - t_start.tv_usec;
cout<<"The target task took "<<total_time<<" us"<<endl;
return 0;
}
运行结果如下:
另外一种使用chrono中的函数实现,例程如下:
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <chrono>
#define MILLION 1000000L
using namespace std;
int main(void)
{
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
/********* target task **************/
sleep(2);
/************************************/
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1)*MILLION;
cout<<"The target task took "<<time_used.count()<<" us"<<endl;
return 0;
}
运行结果如下: