如何优化此程序
How can I optimize this program?
我正在尝试优化一个 c++ 代码,它读取一个整数 M(M<2^31( 并计算 M*M*25.由于 M*M*25 溢出,我以不同的方式编写程序。它在 0.2 秒内完成了 1500 万个整数的测试用例,这非常令人印象深刻,但对于我的项目来说仍然太慢了。如果有人可以使用asm优化代码或重写代码以使其更快,请发布您的代码。这是我的代码:
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector,fast-math")
#pragma comment(linker, "/stack:200000000")
#include <cstdint>
#include <stdio.h>
char buf[1 << 20];
char* p1 = buf;
char* p2 = buf;
inline int getc() {
return (p1 == p2) && (p2 = (p1 = buf) + fread_unlocked(buf, 1, 1 << 20, stdin), p1 == p2) ? EOF : *p1++;
}
inline uint_fast64_t read() {
uint_fast64_t ret = 0;
uint_fast8_t ch = getc();
while (ch >= '0' && ch <= '9') {
ret = (ret << 1) + (ret << 3) + ch - '0';
ch = getc();
}
return ret;
}
inline void write(uint_fast64_t x) {
if (x == 0) {
putchar_unlocked(48);
return;
}
uint_fast32_t stk[20];
uint_fast32_t top = 0;
uint_fast32_t* ptr;
ptr = &stk[0];
while (x) {
*ptr = x % 10;
x /= 10; ptr++;
}
ptr--;
while (ptr >= (&stk[0])) {
putchar_unlocked(*ptr + '0');
ptr--;
}
}
int main()
{
uint_fast64_t a;
while (a = read()) {
if (a != 1)
write(a * a >> 2);
if (a & 1) {
putchar_unlocked('2');
putchar_unlocked('5');
putchar_unlocked('n');
}
else {
putchar_unlocked('0');
putchar_unlocked('0');
putchar_unlocked('n');
}
}
}
我已经优化了程序的I/O。由于我不允许在这个项目中使用 fwrite((,这是我所知道的最快的 I/O 方式。
Gcc 提供了一个 128 位整数类型,其宽度足以存储您的结果。考虑到编译器优化,这应该是解决问题的最快方法
#include <iostream>
#include <stdint.h>
#include <ios>
int main()
{
/*
By default, C++ streams are synchronized with their respective C streams.
Turning off synchrnization may result in faster I/O operations. For details see https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio
*/
std::ios::sync_with_stdio(false);
uint64_t num;
std::cin >> num;
__uint128_t res = (__uint128_t)num * num * 25;
// print res
return 0;
}
注意:128 位整数类型仅适用于 64 位目标
相关文章:
- 为什么我的程序在 O0 和 O2 的优化级别返回不同的结果
- 如何优化以下程序?
- O2优化水平中断程序工作
- 如何优化C++键值程序以获得更快的运行时间
- 为什么警告阻止我们编写优化程序
- 多线程程序卡在优化模式下,但在 -O0 中正常运行
- 优化形状跟踪程序 - C++ OpenCV
- 如何在卷积程序的 c++ 中优化嵌套循环
- 如何优化此程序
- 未经GCC优化而编译的简单C++程序不会产生预期的结果
- Arm GNU编译器:通过多余的强制转换优化的三进制生成的程序集
- 对 constexpr 与内联函数的调用编译为不同的程序集,并禁用优化
- 使用优化编译时的多线程程序块
- C++井字游戏程序优化
- 如果我设置优化 -O3,C++整个程序优化是否在 gcc 中完成
- 是否有可能比 C 中的相同程序(优化)更快地获得 Java 程序
- 针对AT91SAM9 ARM处理器Linux用户空间程序优化FFT和数学运算
- 可能存在VS2012编译器错误(可能在整个程序优化中?)
- 如何在VC++2015全程序优化的情况下正确地从dll中公开接口
- Visual Studio警告C4743:整个程序优化如何影响_fltused