【发布时间】:2020-09-07 23:36:20
【问题描述】:
我有一个用 C++ 计算点积的函数。我想用 -O3 编译器优化来编译这个函数。我的代码库中的其余代码是用 -O0 编译的。为此,我创建了一个包含该函数的静态库,并使用 -O3 编译了该库。然后我将库链接到我的代码。但我没有从我的库中得到优化。
test.cpp
#include "config.h"
int multiply(uint128 *X1, uint128 *Y1, uint128 &ans, int input_length)
{
int i=0;
ans = 0;
if (input_length > 4)
{
for (; i < input_length - 4; i += 4)
{
ans += X1[i] * Y1[i];
ans += X1[i + 1] * Y1[i + 1];
ans += X1[i + 2] * Y1[i + 2];
ans += X1[i + 3] * Y1[i + 3];
}
}
for (; i < input_length; i++)
{
ans += X1[i] * Y1[i];
}
return 0;
}
int main()
{
int len = 500, wrapper = 50;
uint128 a[len], b[len], ans;
auto start = time_now, end = time_now;
long long ctr = 0;
for(int t = 0; t < wrapper; t++)
{
for(int i =0; i < len; i++)
{
a[i] = rand();
b[i] = rand();
}
start = time_now;
multiply(a, b, ans, len);
end = time_now;
ctr += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count();
}
cout<<"time taken: "<<ctr<<endl;
}
Compilation:
g++ -O3 test.cpp -std=c++11
./a.out
time taken: 1372
optimized.hpp
#ifndef OPTIMIZED_HPP
#define OPTIMIZED_HPP
#include <bits/stdc++.h>
using namespace std;
typedef __uint128_t uint128;
int multiply(uint128 *X1, uint128 *Y1, uint128 &ans, int input_length);
#endif
main.cpp
#include "optimized.hpp"
typedef __uint128_t uint128;
#define time_now std::chrono::high_resolution_clock::now()
int main()
{
int len = 500, wrapper = 50;
uint128 a[len], b[len], ans;
auto start = time_now, end = time_now;
long long ctr = 0;
for(int t = 0; t < wrapper; t++)
{
for(int i =0; i < len; i++)
{
a[i] = rand();
b[i] = rand();
}
start = time_now;
multiply(a, b, ans, len);
end = time_now;
ctr += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count();
}
cout<<"time taken: "<<ctr<<endl;
return 0;
}
Compilation:
(the name of the library file is optimized.cpp)
g++ -O3 -g -std=c++11 -c optimized.cpp
ar rcs libfast.a optimized.o
g++ main.cpp libfast.a -std=c++11 -O3
./a.out
time taken: 36140
【问题讨论】:
-
函数模板化了吗?还是内联?
-
没有。问题已编辑。我已经添加了功能。
-
我们还需要查看
main.cpp的源代码,或者一个更简单的程序出现同样的问题,加上它确实出现问题的证据。跨度> -
问题已编辑。 @MikeKinghan
-
你能不能别发照片了
标签: c++ c++11 gcc static-libraries compiler-optimization