[英]Calculating the time taken by a program
Use the series tan{-1}(x) = x – x3 / 3 + x5 / 5 – x7 / 7 + ... to calculate the value of pi. 使用序列tan {-1}(x)= x – x3 / 3 + x5 / 5 – x7 / 7 + ...计算pi的值。 How fast is the convergence?
收敛速度有多快? My attempt:
我的尝试:
/* Calculating the value of pi */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// To calculate tan inverse
float CalculateInverseTan(float fX)
{
float fY = 0;
float fSign = 1;
float fTerm = 0;
int iii = 1;
do
{
float fPow = 1;
int jjj;
// Calculating the power
for (jjj = 1; jjj <= iii; jjj++)
{
fPow *= fX;
}
fTerm = fSign * (fPow / iii);
fY += fTerm;
iii += 2;
fSign *= -1;
} while (fTerm > 0.0001 || fTerm < -0.0001);
return fY;
}
int main()
{
printf("Let x = tan^(-1)(1).\n");
time_t start = time(0);
float fTanInverse1 = CalculateInverseTan(1);
time_t end = time(0);
printf("Therefore x = %f. Time of convergence = %f sec.\nAs x = pi/4, therefore pi = 4x.\nTherefore pi = %f\n", fTanInverse1, difftime(start, end), 4 * fTanInverse1);
return 0;
}
I have managed to calculate the value of pi. 我设法计算出pi的值。 But the time of convergence is always coming as 0.
但是收敛时间总是为0。
Does it look like your program completes in < 1
second? 看起来您的程序在不到
1
秒的时间内完成了吗?
If that is the case, you will get a result of 0
because the time
function has a resolution of only 1
second. 在这种情况下,您将得到
0
的结果,因为time
函数的分辨率仅为1
秒。
You could instead use the clock
function which measures time in terms of ticks of your CPU, then you can convert it back to seconds. 您可以改为使用
clock
功能,该功能根据CPU的滴答度来测量时间,然后可以将其转换回秒。
Use this method. 使用此方法。
#include <time.h>
int main() {
clock_t start, end;
double cpu_time_used;
start = clock();
… /* Do the work. */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
return 0;
}
Use the cpu time To get a process CPU time, you can also use the clock function. 使用cpu时间要获取进程的CPU时间,您还可以使用时钟功能。 This is also declared in the header file `time.h'.
这也在头文件“ time.h”中声明。 you can use a code like this,
您可以使用这样的代码,
`double cpu_time; `double cpu_time;
clock_t start = clock(); clock_t start = clock();
/* your function */ / *您的功能* /
clock_t end = clock(); clock_t end = clock();
cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;` cpu_time =(((double)(end-start)))/ CLOCKS_PER_SEC;`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.