轮子——代码的运行耗时记录

在设计并实现算法时,往往需要对比下不同算法的运行耗时情况,本文记录了不同编程语言实现代码运行耗时检测的方式,不定时维护补充。

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;
}

运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值