C语言学习之时钟函数clock()函数
2017-03-25 10:19
204 查看
// nomial.cpp : Defines the entry point for the console application.
//多项式求解
//计时函数
//clock():从捕捉程序开始运行到clock()函数被调用所耗费的时间,这个时间单位是
//clock tick,即”时钟打点“,常数CLK_TCK:机器时钟每秒所走的时钟打点数
//包含头文件<time.h>
//fx = a+x(b+x(...))
//多项式求解
//计时函数
//clock():从捕捉程序开始运行到clock()函数被调用所耗费的时间,这个时间单位是
//clock tick,即”时钟打点“,常数CLK_TCK:机器时钟每秒所走的时钟打点数
//包含头文件<time.h>
//fx = a+x(b+x(...))
#include "stdafx.h" #include <stdlib.h> #include <math.h>//for pow() #include <time.h> #define MAXN 10//多项式最大项数 #define MAXK 1e7//被测函数最大重复调用次数,注意指数为一e7,不是小写的L,因为一次计算运行太快,可能不足一个时钟计数单位 clock_t start, stop;//clock_t是clock()函数返回类型 double duration; //笨方法 double Function1(int n, double a[], double x) { int i; double p = a[0]; for (i = 1; i < n; i++) p += (a[i] * pow(x, i));//指数次方共相乘i-1次,再乘以a[i],所以共相乘i次,所以乘法的总次数为(1+2+...+n) return p; } double Function2(int n, double a[], double x) { int i; double p = a ; for (i = n; i > 0; i--) p = a[i - 1] + x*p;//共做了n次乘法 return p; } int main() { int i; double a[MAXN];//存储多项式的系数 for (i = 0; i < MAXN; i++) a[i] = (double)i; //可以将以下语句设计成一个函数调用 start = clock();//开始计时 for(i = 0;i < MAXK;i++) Function1(MAXN-1,a,1.1); stop = clock();//停止计时 duration = ((double)(stop - start) / CLK_TCK/MAXK); printf("tick1 = %f\n", (double)(stop - start)); printf("duration1 = %6.2e\n", duration); start = clock();//开始计时 for (i = 0; i < MAXK; i++) Function1(MAXN - 1, a, 1.1); Function2(MAXN - 1, a, 1.1); stop = clock();//停止计时 duration = ((double)(stop - start) / CLK_TCK/MAXK); printf("tick2 = %f\n", (double)(stop - start)); printf("duration2 = %6.2e\n", duration); system("pause"); return 0; }
相关文章推荐
- 学习C语言对文件的操作函数
- C语言学习零碎整理(3):sprintf函数
- 函数07 - 零基础入门学习C语言38
- C语言深入学习--checklist6:函数、变量
- 函数09 - 零基础入门学习C语言40
- 学习C语言的函数
- C语言中基本的输入和输出函数的用法第一讲(C语言学习随笔三)
- 函数06 - 零基础入门学习C语言37
- 函数05 - 零基础入门学习C语言36
- 学习C语言_指针_4_通过指针使被调函数修改主调函数
- what's in string? c语言string类函数实现汇总 都是学习使用指针的好例子啊(算是读书摘抄和笔记吧)
- 函数02 - 零基础入门学习C语言33
- 函数01 - 零基础入门学习C语言32
- 函数06 - 零基础入门学习C语言37
- 函数04 - 零基础入门学习C语言35
- 从零开始学习C语言(一)之读取文本文件(函数fgets)
- 函数01 - 零基础入门学习C语言32
- 函数03 - 零基础入门学习C语言34
- 函数08 - 零基础入门学习C语言39
- 学习笔记——atoi函数的用法及用C语言实现atoi