如何测量 C 代码的运行时间比较? [英] How can i measure running time comparison of C code?
本文介绍了如何测量 C 代码的运行时间比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例代码 1:
const int N=100000;
for(int j=0;j<N;j++){
arr1[j] += a1[j];
arr2[j] += a2[j];
}
示例代码 2:
for(int j=0;j<N;j++){
arr1[j] += a1[j];
}
for(int j=0;j<N;j++){
arr2[j] += a2[j];
}
我需要计算这些代码块的运行时间.是否有任何工具(基准)来计算它?
I need to calculate the running time of these block of code. Is there any tool(benchmark) to calculate it?
推荐答案
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
const int N=100000;
void time_first() {
struct timeval start, mid, end;
long mtime, seconds, useconds;
gettimeofday(&start, NULL);
for(int j=0;j<N;j++){
arr1[j] += a1[j];
arr2[j] += a2[j];
}
gettimeofday(&end, NULL);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
printf("First elapsed time: %ld milliseconds\n", mtime);
}
void time_second() {
struct timeval start, mid, end;
long mtime, seconds, useconds;
gettimeofday(&start, NULL);
for(int j=0;j<N;j++){
arr1[j] += a1[j];
}
for(int j=0;j<N;j++){
arr2[j] += a2[j];
}
gettimeofday(&end, NULL);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
printf("Second elapsed time: %ld milliseconds\n", mtime);
}
int main() {
initialize arr1, a1 and a2
time_first();
time_second();
return 0;
}
这篇关于如何测量 C 代码的运行时间比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文