执行时间的差异
Difference on Execution Time
我正在尝试测量点积的执行时间,但我发现差异取决于用于存储最终结果的变量,即,当使用整数时,结果为 0ms,但当使用元素时array 时间要高很多。
会不会和编译器有关,当使用整型变量时,是否可以对循环进行向量化?
这是我的代码
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
void main(int argc, char* argv[])
{
int* a = new int[2000000000];
for (unsigned long long i = 0; i < 2000000000; i++)
a[i] = 1;
clock_t t1 = clock();
int nResult = 0;
for (unsigned long long i = 0; i < 2000000000; i++)
nResult += a[i] * a[i];
clock_t t2 = clock();
cout << "Execution time = " << (int)(1000 * ((t2 - t1) / (double)CLOCKS_PER_SEC)) << " ms" << endl;
t1 = clock();
int b[1] = {0};
for (unsigned long long i = 0; i < 2000000000; i++)
b[0] += a[i] * a[i];
t2 = clock();
cout << "Execution time = " << (int)(1000 * ((t2 - t1) / (double)CLOCKS_PER_SEC)) << " ms" << endl;
delete[] a;
getchar();
return;
}
这是输出
Execution time = 0 ms
Execution time = 702 ms
在此先感谢您的帮助
我认为这甚至与矢量化无关。即使使用 SIMD 指令,您也不会下降到平坦的 0 毫秒。
然而,似乎正在发生的是循环已被完全删除。您永远不会使用 nResult
的值,即使您使用了,优化器也能够猜测该值是什么,并在编译时将其简单地放入变量中。
基准测试是一个违反直觉的主题,您需要禁用一些编译器优化来实际测量某些东西,同时仍然对正常程序中出现的优化代码进行基准测试。
您可能想看看这个演讲,它非常擅长解释如何正确地对代码进行基准测试:https://youtu.be/nXaxk27zwlk
我正在尝试测量点积的执行时间,但我发现差异取决于用于存储最终结果的变量,即,当使用整数时,结果为 0ms,但当使用元素时array 时间要高很多。
会不会和编译器有关,当使用整型变量时,是否可以对循环进行向量化?
这是我的代码
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
void main(int argc, char* argv[])
{
int* a = new int[2000000000];
for (unsigned long long i = 0; i < 2000000000; i++)
a[i] = 1;
clock_t t1 = clock();
int nResult = 0;
for (unsigned long long i = 0; i < 2000000000; i++)
nResult += a[i] * a[i];
clock_t t2 = clock();
cout << "Execution time = " << (int)(1000 * ((t2 - t1) / (double)CLOCKS_PER_SEC)) << " ms" << endl;
t1 = clock();
int b[1] = {0};
for (unsigned long long i = 0; i < 2000000000; i++)
b[0] += a[i] * a[i];
t2 = clock();
cout << "Execution time = " << (int)(1000 * ((t2 - t1) / (double)CLOCKS_PER_SEC)) << " ms" << endl;
delete[] a;
getchar();
return;
}
这是输出
Execution time = 0 ms
Execution time = 702 ms
在此先感谢您的帮助
我认为这甚至与矢量化无关。即使使用 SIMD 指令,您也不会下降到平坦的 0 毫秒。
然而,似乎正在发生的是循环已被完全删除。您永远不会使用 nResult
的值,即使您使用了,优化器也能够猜测该值是什么,并在编译时将其简单地放入变量中。
基准测试是一个违反直觉的主题,您需要禁用一些编译器优化来实际测量某些东西,同时仍然对正常程序中出现的优化代码进行基准测试。
您可能想看看这个演讲,它非常擅长解释如何正确地对代码进行基准测试:https://youtu.be/nXaxk27zwlk