我正在做一个编程作业,结果很奇怪。
其思想是计算处理器的计时次数和运行算法所需的时间。
通常代码运行得很快,所用的时间为0秒,但我注意到,在开始和结束时,处理器滴答数都为0,从而导致所用的处理器滴答数为0。
我使用usleep
添加了一个延迟,因此所用的时间不是零,但是处理器时钟仍然是零,时间戳之间的计算仍然是零。
这几天来我一直在思考这个问题,我无法解决这个问题,任何建议都是非常受欢迎的。
我的代码如下:
/* This program takes an input "n". If n is even it divides n by 2
* If n is odd, it multiples n by 3 and adds 1. Each time through the loop
* it iterates a counter.
* It continues until n is 1
*
* This program will compute the time taken to perform the above algorithm
*/
#include <stdio.h>
#include <time.h>
void delay(int);
int main(void) {
int n, i = 0;
time_t start, finish, duration;
clock_t startTicks, finishTicks, diffTicks;
printf("Clocks per sec = %d\n", CLOCKS_PER_SEC);
printf("Enter an integer: ");
scanf("%d", &n); // read value from keyboard
time(&start); // record start time in ticks
startTicks = clock();
printf("Start Clock = %s\n", ctime(&start));
printf("Start Processor Ticks = %d\n", startTicks);
while (n != 1) { // continues until n=1
i++; // increment counter
printf("iterations =%d\t", i); // display counter iterations
if (n % 2) { // if n is odd, n=3n+1
printf("Input n is odd!\t\t");
n = (n * 3) + 1;
printf("Output n = %d\n", n);
delay(1000000);
} else { //if n is even, n=n/2
printf("Input n is even!\t");
n = n / 2;
printf("Output n = %d\n", n);
delay(1000000);
}
}
printf("n=%d\n", n);
time(&finish); // record finish time in ticks
finishTicks = clock();
printf("Stop time = %s\n", ctime(&finish));
printf("Stop Processor Ticks = %d\n", finishTicks);
duration = difftime(finish, start); // compute difference in time
diffTicks = finishTicks - startTicks;
printf("Time elapsed = %2.4f seconds\n", duration);
printf("Processor ticks elapsed = %d\n", diffTicks);
return (n);
}
void delay(int us) {
usleep(us);
}
编辑:所以在进一步研究之后,我发现
usleep()
不会影响程序的运行时间,所以我在asm中写了一个延迟函数。现在我得到了一个处理器计时的值,但是运行算法的时间仍然是零秒。void delay(int us) {
for (int i = 0; i < us; i++) {
__asm__("nop");
}
}
最佳答案
您可以使用以下公式计算经过的时间。
double timeDiff = (double)(EndTime - StartTime) / CLOCKS_PER_SEC.
这是伪代码。
void CalculateTime(clock_t startTime, clock_t endTime)
{
clock_t diffTime = endTime - startTime;
printf("Processor time elapsed = %lf\n", (double)diffTime /CLOCKS_PER_SEC);
}
希望这有帮助。
关于c - 在C问题中使用time()和clock(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35674300/