如何优化此程序

How can I optimize this program?

本文关键字:程序 优化 何优化      更新时间:2023-10-16

我正在尝试优化一个 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 位目标