计算一个程序所用的时间
Calculating the time taken by a program
使用级数tan{-1}(x) = x – x3 / 3 + x5 / 5 – x7 / 7 + ...来计算pi的值。收敛速度有多快?
我的尝试:
/* 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;
}
我已经计算出 pi 的值了。但是收敛的时间总是0.
您的程序看起来是否在 < 1
秒内完成?
如果是这样,您将得到 0
的结果,因为 time
函数的分辨率只有 1
秒。
您可以改用 clock
函数,该函数根据 CPU 的刻度来测量时间,然后您可以将其转换回秒。
使用cpu时间
要获得一个进程CPU的时间,也可以使用clock函数。这也在头文件“time.h”中声明。
你可以使用这样的代码,
`双 cpu_time;
clock_t开始=时钟();
/* 你的函数 */
clock_t 结束=时钟();
cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;`
使用这个方法。
#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;
}
使用级数tan{-1}(x) = x – x3 / 3 + x5 / 5 – x7 / 7 + ...来计算pi的值。收敛速度有多快? 我的尝试:
/* 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;
}
我已经计算出 pi 的值了。但是收敛的时间总是0.
您的程序看起来是否在 < 1
秒内完成?
如果是这样,您将得到 0
的结果,因为 time
函数的分辨率只有 1
秒。
您可以改用 clock
函数,该函数根据 CPU 的刻度来测量时间,然后您可以将其转换回秒。
使用cpu时间 要获得一个进程CPU的时间,也可以使用clock函数。这也在头文件“time.h”中声明。 你可以使用这样的代码,
`双 cpu_time;
clock_t开始=时钟();
/* 你的函数 */
clock_t 结束=时钟();
cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;`
使用这个方法。
#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;
}