金融编程—返回计算时间

论坛 期权论坛 程序化     
吴宇   2015-12-15 16:57   25721   1

程序的运行效率对金融工程计算至关重要,提高效率主要靠算法,次要靠硬件。反应程序效率最直接的办法是观察运行时间。在MATLAB中可以应用tic,toc插入到程序中返回程序段的运行时间,其实在C++中也可以实现上述功能。
    先写一个头文件“runtime.h”,转换时间格式
#include<iostream>
#include<time.h>
using namespace std;
void runtime (int t)
{
t=abs(t);
int n=t/CLOCKS_PER_SEC;
int r=t-CLOCKS_PER_SEC*n;
cout<<endl;
cout<<"运行时间:";
if (n!=0)
{
  if (n/60==0)
   cout<<n<<" 秒 "<<r<<" 毫秒"<<endl;
  else
  {
   if (n/3600==0)
    cout<<n/60<<" 分 "<<n`<<" 秒 "<<r<<" 毫秒"<<endl;
   else
    cout<<n/3600<<" 小时 "<<(n600)/60<<\
    " 分 "<<(n600)`<<" 秒 "<<r<<" 毫秒"<<endl;
  }
}
else
  cout<<t<<" 毫秒"<<endl;
}
    程序中的CLOCKS_PER_SEC反映了CPU时间精度,我的系统CLOCKS_PER_SEC=1000,所以最小时间单位是0.001秒,即1毫秒。你可以通过以下程序查看自己系统的CLOCKS_PER_SEC,相应的修改头文件。
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
cout<<CLOCKS_PER_SEC<<endl;
}
    下面写一个小程序并返回运行时间。
#include<iostream>
#include<math.h>
#include"runtime.h"
using namespace std;
long Fibonacci (long n) //递归法计算Fibonacci数列(算法比较耗时)
{
if (n==1||n==2)
  return 1;
else
  return Fibonacci(n-1)+Fibonacci(n-2);
}
int main()
{
clock_t start=clock();
cout<<Fibonacci(40)<<endl;
clock_t finish=clock();
runtime(finish-start);
return 0;
}
    要想查看程序段的运行时间,操作和MATLAB中的tic,toc命令用法一样,只要将tic,toc换成start=clock(),finish=clock(),但是要声明变量类型clock_t(用int好像也可以)。
我的电脑用了6秒,你的呢?

分享到 :
0 人收藏
萍水相逢,尽是他乡之客

1 个回复

倒序浏览
2#
abel   | 2017-1-9 09:29:36 发帖IP地址来自 重庆江北区
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:38337
帖子:3370
精华:36
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP