如何测量C代码的运行时间比较
How can i measure running time comparison of C code?
示例代码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];
}
我需要计算这些代码块的运行时间。有什么工具(基准)可以计算吗?
如果您在包含它的系统下运行,您可以在time
:下执行它
$ time ./benchmark1
和
$ time ./benchmark2
#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 millisecondsn", 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 millisecondsn", mtime);
}
int main() {
initialize arr1, a1 and a2
time_first();
time_second();
return 0;
}
相关文章:
- KMP算法和LPS表构造的运行时间
- 如何减少代码的运行时间以对齐文本?
- 此代码中运行时间错误的原因是什么
- 一行代码的Arduino运行时间
- 该递归代码用于计算指数的运行时间是多少
- (如何)我可以使用LLVM机器代码分析器预测代码片段的运行时间
- 我的代码在大O时间中的运行时间
- 如何在Visual Studio中设置C /C代码仅在一个线程中运行以测试运行时间
- 为什么这两个代码之间的运行时间差异这么长
- 更改Linux用户从C/C 代码运行时间
- 为什么相同的代码运行时间不同
- 运行时间比较 - 类似的代码运行速度慢 4 倍
- 以下 Prim 算法代码的运行时间
- 调试代码的运行时间比发布代码长几个数量级
- 在展开的链表上运行大约需要40%的代码运行时间——有什么明显的方法可以优化它吗
- 如何测量C代码的运行时间比较
- 确定代码的运行时间
- 测量c++和CUDA代码的运行时间
- 如何进一步减少此代码的运行时间
- C++ 代码随着时间的推移运行速度变慢