IT이야기

Fortran은 많은 계산을 위해 C보다 최적화가 더 쉽습니까?

cyworld 2022. 6. 18. 09:31
반응형

Fortran은 많은 계산을 위해 C보다 최적화가 더 쉽습니까?

가끔 Fortran이 C보다 빠르거나 더 빠를 수 있다는 것을 알았습니다.그게 정말 사실이에요?Fortran을 잘 모르는 것은 인정합니다만, 지금까지 본 Fortran 코드에는 C에는 없는 기능이 포함되어 있지 않습니다.

사실이라면 이유를 알려주세요.숫자 계산에는 어떤 언어나 lib가 좋은지 말하지 말아주세요.어플리케이션이나 lib를 만들 생각은 없습니다.그냥 궁금해서요.

두 언어에는 유사한 기능 집합이 있습니다.퍼포먼스의 차이는 EQUALITENCE 문을 사용하지 않는 한 Fortran이 에일리어스는 허용되지 않는다고 말하고 있기 때문입니다.에일리어스가 있는 코드는 모두 Fortran이 유효하지 않지만 이러한 오류를 검출하는 것은 프로그래머가 아니라 컴파일러가 결정합니다.따라서 Fortran 컴파일러는 메모리 포인터의 가능한 에일리어싱을 무시하고 보다 효율적인 코드를 생성할 수 있도록 합니다.C의 예를 보겠습니다.

void transform (float *output, float const * input, float const * matrix, int *n)
{
    int i;
    for (i=0; i<*n; i++)
    {
        float x = input[i*2+0];
        float y = input[i*2+1];
        output[i*2+0] = matrix[0] * x + matrix[1] * y;
        output[i*2+1] = matrix[2] * x + matrix[3] * y;
    }
}

이 기능은 최적화 후 Fortran 대응 기능보다 느리게 실행됩니다.왜 그럴까?출력 배열에 값을 쓰는 경우 행렬 값을 변경할 수 있습니다.결국 포인터는 오버랩되어 같은 메모리 청크를 가리킬 수 있습니다.int포인터!)C 컴파일러는 모든 계산에 대해 4개의 매트릭스 값을 메모리에서 새로고침하도록 강제됩니다.

Fortran에서는 컴파일러가 매트릭스 값을 한 번 로드하여 레지스터에 저장할 수 있습니다.Fortran 컴파일러는 포인터/어레이가 메모리에서 겹치지 않는다고 가정하기 때문에 그렇게 할 수 있습니다.

다행히 이 문제에 대처하기 위해 키워드와 완전 에일리어싱이 C99 표준에 도입되었습니다.이 기능은 현재 대부분의 C++ 컴파일러에서도 잘 지원됩니다.키워드를 사용하면 프로그래머가 포인터가 다른 포인터와 에일리어스하지 않는다는 것을 컴파일러에 힌트를 줄 수 있습니다.엄밀한 에일리어싱은 프로그래머가 다른 타입의 포인터가 절대 겹치지 않을 것을 약속하는 것을 의미합니다. 예를 들어,double*와 중복되지 않습니다.int*(특별히 예외로 한다)char*그리고.void*어떤 것과도 겹칠 수 있습니다).

그것들을 사용하면 C와 Fortran에서 같은 속도를 얻을 수 있습니다.단, 를 사용할 수 있는restrict퍼포먼스 크리티컬 기능이 있는 키워드만 지정하면 C(및 C++) 프로그램이 훨씬 안전하고 쓰기 쉽다는 것을 의미합니다.예를 들어, 잘못된 Fortran 코드를 고려합니다.CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30)대부분의 Fortran 컴파일러는 경고 없이 컴파일되지만 일부 컴파일러, 일부 하드웨어 및 일부 최적화 옵션에서만 볼 수 있는 버그가 발생합니다.

네, 1980년, 2008년?에 따라 다릅니다.

제가 전문적으로 프로그래밍을 시작했을 때 Fortran의 속도 우위가 도전받고 있었습니다.닥터 돕스를 읽고 나이든 프로그래머들에게 기사를 얘기했던 게 기억나요. 다들 웃었어요.

이에 대해 이론적인 견해와 실제적인 견해 두 가지를 가지고 있습니다.오늘날의 Fortran은 이론적으로 C/C++ 또는 어셈블리 코드를 허용하는 어떤 언어에도 내재적 이점이 없습니다.실제로 Fortran은 오늘날에도 여전히 숫자 코드의 최적화를 중심으로 구축된 역사와 문화의 유산의 이점을 누리고 있습니다.

Fortran 77까지 언어 설계 고려사항은 최적화를 주안점으로 하고 있었습니다.컴파일러 이론과 테크놀로지의 상태 때문에 이것은 종종 컴파일러가 코드를 최적화할 수 있는 최선의 기회를 주기 위해 기능과 기능을 제한하는 것을 의미했습니다.Fortran 77은 속도를 위해 기능을 희생하는 전문적인 경주용 자동차라고 생각하는 것이 좋은 비유입니다.오늘날 컴파일러는 모든 언어에 걸쳐 향상되었으며 프로그래머의 생산성 향상 기능이 더욱 중시되고 있습니다.그러나 여전히 과학 컴퓨팅의 속도에 주로 관심을 갖는 곳이 있습니다.이러한 사람들은 Fortran 프로그래머였던 사람들로부터 코드, 훈련 및 문화를 물려받았을 가능성이 높습니다.

코드 최적화에 대해 이야기하기 시작할 때, 많은 문제가 있으며, 이를 이해하는 가장 좋은 방법은 빠른 숫자 코드를 갖는 것이 직업인 사람들이 있는 곳에 잠복하는 것이다.그러나 이러한 중요한 코드는 일반적으로 코드 전체 행의 극히 일부이며 매우 전문화되어 있습니다.Fortran 코드의 많은 부분은 다른 언어의 다른 많은 코드와 마찬가지로 "비효율적"이므로 최적화가 이러한 코드의 주요 관심사가 되지 않아야 합니다.

Fortran의 역사와 문화에 대해 배울 수 있는 훌륭한 장소는 위키피디아입니다.Fortran Wikipedia 엔트리는 훌륭합니다.Fortran 커뮤니티를 위해 시간과 노력을 들인 분들께 감사드립니다.

(이 답변의 단축판은 Nils가 시작한 훌륭한 스레드에 대한 코멘트였을 것입니다만, 저는 그럴 업보가 없습니다.사실 저는 이 주제에 대한 저의 주된 경험인 불꽃 전쟁이나 언어 편견이 아니라 이 스레드에 실제 정보 내용과 공유가 포함되어 있지 않았다면 아무것도 쓰지 않았을 것입니다.너무 벅차서 사랑을 나눠야 했어요.)

Fortran은 어느 정도 컴파일러 최적화를 염두에 두고 설계되었습니다.이 언어는 컴파일러가 병렬 처리를 이용할 수 있는 어레이 전체의 조작을 지원합니다(특히 멀티코어 프로세서의 경우).예를들면,

고밀도 행렬 곱셈은 다음과 같습니다.

matmul(a,b)

벡터 x의 L2 노름은 다음과 같습니다.

sqrt(sum(x**2))

또한 다음과 같은 문장이 있습니다.FORALL,PURE&ELEMENTAL절차 등은 코드를 최적화하는 데 도움이 됩니다.이 단순한 이유 때문에 Fortran의 포인터조차 C만큼 유연하지 않습니다.

곧 출시될 Fortran 표준(2008)에는 병렬 코드를 쉽게 작성할 수 있는 공동 배열이 있습니다.G95(오픈 소스)와 CRAY의 컴파일러는 이미 지원되고 있습니다.

따라서 Fortran은 컴파일러가 C/C++보다 더 잘 최적화/병렬화할 수 있기 때문에 고속화할 수 있습니다.하지만 인생의 다른 모든 것과 마찬가지로 좋은 컴파일러와 나쁜 컴파일러가 있습니다.

Fortran에게 유리한 포인트는 Fortran이 벡터 및 어레이 기반의 수학 표현에 조금 더 적합한 언어라는 것입니다.위에서 지적한 포인터 분석 문제는 실제로는 실제입니다.휴대용 코드는 컴파일러에게 무언가를 말할 수 있다고 가정할 수 없기 때문입니다.계산식을 도메인 모양에 가깝게 표현하면 항상 이점이 있습니다.C에는 실제로 어레이가 전혀 없습니다.자세히 보면 이와 같은 동작을 하고 있을 뿐입니다.Fortran은 진짜 미궁을 가지고 있다.그 때문에, 특히 병렬 머신에 대해서, 특정의 알고리즘에 대해서 컴파일을 용이하게 할 수 있습니다.

런타임 시스템이나 호출 규약 등의 깊은 곳에서 C와 현대의 Fortran은 매우 유사하기 때문에 어떤 점이 다른지 알 수 없습니다.여기서 C는 C의 베이스입니다.C++는 퍼포먼스 특성이 전혀 다른 문제입니다.

빠르고 심플: 둘 다 같은 속도이지만 Fortran이 더 심플합니다.최종적으로 가장 빠른 것은 알고리즘에 따라 다르지만, 어쨌든 상당한 속도 차이는 없습니다.2015년 독일 슈투트가르드 고성능 컴퓨팅 센터에서 열린 Fortran 워크숍에서 배운 내용입니다.저는 Fortran과 C와 함께 일하며 이 의견을 공유합니다.

설명:

C는 운영체제를 쓰도록 설계되어 있습니다.따라서 고성능 코드를 쓸 수 있는 자유도가 필요 이상으로 높아집니다.일반적으로 이것은 문제가 되지 않지만 신중하게 프로그래밍하지 않으면 코드 속도가 느려질 수 있습니다.

Fortran은 과학 프로그래밍을 위해 설계되었습니다.이 때문에, Fortran 의 주된 목적이기 때문에, 구문에 의한 고속 코드의 기입을 서포트하고 있습니다.여론과 달리 Fortran은 구식 프로그래밍 언어가 아닙니다.최신 표준은 2010년이며 새로운 컴파일러는 정기적으로 발행됩니다.이는 대부분의 고성능 코드가 Fortran에서 작성되기 때문입니다.Fortran은 컴파일러 디렉티브로서 최신 기능을 더욱 지원합니다(C 플러그마).

예: 함수(포트란: 서브루틴)의 입력 인수로 큰 구조를 지정하려고 합니다.함수 내에서 인수는 변경되지 않습니다.

C는 참조에 의한 콜과 값에 의한 콜의 양쪽 모두를 서포트하고 있습니다.이것은 편리한 기능입니다.이 경우 프로그래머가 실수로 값별 호출을 사용할 수 있습니다.이 경우 구조가 먼저 메모리 내에 복사되어야 하므로 속도가 상당히 느려집니다.

Fortran은 참조에 의해서만 콜과 함께 동작합니다.이것에 의해, 프로그래머가 정말로 값에 의한 콜 연산을 원할 경우, 수동으로 구조를 카피할 수 밖에 없습니다.이 경우 Fortran은 참조 콜을 통해 자동으로 C 버전만큼 빠릅니다.

Fortran과 C의 속도 차이는 컴파일러 최적화와 특정 컴파일러가 사용하는 기본 연산 라이브러리의 함수에 가깝습니다.Fortran 고유의 C보다 빠른 것은 없습니다.

어쨌든, 훌륭한 프로그래머는 어떤 언어로든 Fortran을 쓸 수 있습니다.

Fortran이 더 빠를 수 있는 몇 가지 이유가 있습니다.하지만, 그들이 얼마나 중요한지는 중요하지 않거나, 어떻게든 해결할 수 있기 때문에, 그것은 문제가 되지 않을 것이다.오늘날 Fortran을 사용하는 주된 이유는 레거시 애플리케이션을 유지 또는 확장하기 위해서입니다.

  • 함수에 관한 PURE 키워드 및 ELEMENTAL 키워드.이것들은 부작용이 없는 기능들이다.이것에 의해, 컴파일러가 같은 함수가 같은 값으로 호출되는 것을 알고 있는 경우에 최적화가 가능하게 됩니다.주의: GCC는 언어의 확장으로서 「순수」를 실장합니다. 다른 컴파일러도 마찬가지입니다. 모듈 간 분석에서도 이 최적화를 수행할 수 있지만 어렵습니다.

  • 개별 요소가 아닌 어레이를 처리하는 표준 기능 세트입니다.sin(), log(), sqrt() 등은 스칼라 대신 배열을 사용합니다.이것에 의해, 루틴의 최적화가 용이하게 됩니다.이러한 기능이 인라인 또는 빌트인 경우 대부분의 경우 자동 벡터라이제이션에 의해 동일한 이점이 있습니다.

  • 빌트인 콤플렉스 타입.이론상으로는 컴파일러가 특정 명령어를 재정렬하거나 삭제할 수 있지만, 같은 이점을 얻을 수 있습니다.struct { double re; double im; };C에서 사용되는 관용어.작업자가 Fortran의 복잡한 유형에 대해 작업하기 때문에 개발 속도가 빨라집니다.

어떤 언어가 다른 언어보다 빠르다는 것은 없기 때문에, 적절한 대답은 "아니오"입니다.

Fortran 컴파일러 X로 컴파일된 코드가 C 컴파일러 Y로 컴파일된 동등한 코드보다 빠릅니까?물론 이 질문에 대한 답은 어떤 컴파일러를 선택하느냐에 따라 달라집니다.

또 다른 질문은 "컴파일러 최적화와 동일한 노력을 기울인다면 어떤 컴파일러가 더 빠른 코드를 생성하겠는가?"와 같은 것입니다.이에 대한 답은 사실 Fortran이 될 것입니다.Fortran 컴파일러에는 다음과 같은 확실한 이점이 있습니다.

  • Fortran은 컴파일러를 절대 사용하지 않겠다고 맹세했던 시절에 어셈블리와 경쟁해야 했기 때문에 속도를 높이기 위해 설계되었습니다.C는 유연하게 설계되어 있습니다.
  • Fortran의 틈새 시장은 수치 경색이었다.이 도메인 코드는 결코 충분히 빠르지 않습니다.그래서 언어를 효율적으로 유지해야 한다는 압박감이 항상 있었습니다.
  • 컴파일러 최적화 연구의 대부분은 Fortran 번호 처리 코드 속도를 높이는 데 관심이 있는 사람들에 의해 이루어지기 때문에 Fortran 코드를 최적화하는 것은 다른 컴파일 언어를 최적화하는 것보다 훨씬 더 잘 알려진 문제이며 새로운 혁신이 Fortran 컴파일러에 먼저 나타납니다.
  • Biggie: C는 Fortran보다 훨씬 더 많은 포인터 사용을 장려합니다.이로 인해 C 프로그램에서 데이터 항목의 잠재적 범위가 대폭 증가하여 최적화가 훨씬 어려워집니다.또한 Ada는 이 영역에서 C보다 훨씬 우수하며 일반적으로 사용되는 Fortran77보다 훨씬 더 현대적인 OO 언어입니다.만약 당신이 C보다 빠른 코드를 생성할 수 있는 OO langauge를 원한다면, 이것은 당신의 옵션입니다.
  • Fortran 컴파일러의 고객은 C 컴파일러의 고객보다 최적화에 더 신경을 쓰는 경향이 있습니다.

그러나 C 컴파일러의 최적화에 많은 노력을 기울여 플랫폼의 Fortran 컴파일러보다 더 나은 코드를 생성하는 것을 막을 수는 없습니다.실제로 C 컴파일러에 의한 대규모 판매로 인해 이 시나리오는 실현 가능성이 매우 높아집니다.

언어를 모르기 때문에 여기에 많은 답이 있다니 웃기다.이것은 특히 FORTRAN 77 코드를 열어 오래된 C/C++ 프로그래머에게 해당되며 취약점에 대해 논의합니다.

속도 문제는 주로 C/C++와 Fortran의 질문이라고 생각합니다.거대 코드에서는 항상 프로그래머에 의존합니다.Fortran이 능가하는 언어의 특징과 C가 능가하는 특징이 있습니다.그래서 2011년에는 어느 것이 더 빠른지 아무도 말할 수 없다.

언어 자체에 대해 Fortran은 현재 전체 OOP 기능을 지원하며 완전히 역호환됩니다.저는 Fortran 2003을 충분히 사용해 왔습니다만, 그것을 사용하는 것은 매우 즐거웠다고 말하고 싶습니다.Fortran 2003이 C++에 아직 뒤처져 있는 측면도 있습니다만, 사용 상황에 대해 살펴보겠습니다.Fortran은 대부분 수치 계산을 위해 사용되며 속도 때문에 아무도 화려한 C++ OOP 기능을 사용하지 않습니다.하이 퍼포먼스 컴퓨팅에서는 C++는 갈 곳이 거의 없습니다(MPI 표준을 보면 C++는 더 이상 사용되지 않는다는 것을 알 수 있습니다.

요즘에는 Fortran과 C/C++로 간단히 혼합 언어 프로그래밍을 할 수 있습니다.Fortran에는 GTK+용 인터페이스도 있습니다.무료 컴파일러(gfortran, g95)와 우수한 상용 컴파일러가 많이 있습니다.

Fortran, C, C++의 속도를 netlib의 클래식한 Levine-Callahan-Dongara 벤치마크와 비교합니다.OpenMP를 사용하는 다국어 버전은 http://sites.google.com/site/tprincesite/levine-callahan-dongarra-vectors 입니다.C는 자동번역 및 특정 컴파일러의 제한 및 프래그마 삽입에서 시작되었기 때문에 더 추합니다.C++는 해당하는 경우 STL 템플릿을 사용하는 C일 뿐입니다.내 생각에 STL은 유지관리성을 향상시키는지에 대한 혼합형 가방이다.

자동 기능의 인라인 실행은 최적화가 어느 정도 개선되는지를 확인하기 위해 최소한으로 그쳤는데, 이는 예가 인라인에 거의 의존하지 않는 전통적인 Fortran 관행에 기초하기 때문입니다.

지금까지 가장 널리 사용되고 있는 C/C++ 컴파일러는 자동 벡터화가 없기 때문에 이러한 벤치마크에 크게 의존하고 있습니다.

바로 앞에 게시된 글을 참고하십시오. Fortran에서 평가의 보다 빠르고 정확한 순서를 지시하기 위해 괄호를 사용하는 예가 몇 가지 있습니다.기존의 C 컴파일러에는 보다 중요한 최적화를 무효로 하지 않으면 괄호를 표시할 수 있는 옵션이 없습니다.

저는 취미 프로그래머이고 두 언어 모두 "평균"입니다.C(또는 C++) 코드보다 Fortran 코드를 빨리 쓰는 것이 더 쉽다는 것을 알았습니다.Fortran과 C는 모두 (오늘날 표준으로) "역사적인" 언어이며, 많이 사용되고 있으며, 자유롭고 상업적인 컴파일러를 잘 지원하고 있습니다.

역사적인 사실인지는 모르겠지만 Fortran은 병렬/분포/벡터화/많은 코어들이 모여있도록 만들어진 것처럼 느껴집니다.오늘날 속도란 거의 '표준 측정 기준'입니다. "확장 가능합니까?"

순수한 CPU 크런치를 위해 나는 Fortran을 사랑한다.I/O와 관련된 모든 것은 C와 함께 작업하는 것이 더 쉽다고 생각합니다(어쨌든 어느 경우든 어렵습니다).

물론 병렬 연산 부하 코드의 경우 GPU를 사용하는 것이 좋습니다.C와 Fortran 모두 CUDA/OpenCL 인터페이스(현재는 OpenACC)가 거의 통합되어 있습니다.

My moderately objective answer is : If you know both language equally well/poorly then i think Fortran is faster because i find it easier to write parallel/distributed code in Fortran than C. (once you understood that you can write "freeform" fortran and not just strict F77 code)

Here is a 2nd answer for those willing to downvote me because they don't like the 1st answer : Both language have the features required to write high-performance code. So it's dependent of the algorithm you're implementing (cpu intensive ? io intensive ? memory intensive?), the hardware (single cpu ? multi-core ? distribute supercomputer ? GPGPU ? FPGA ?), your skill and ultimately the compiler itself. Both C and Fortran have awesome compiler. (i'm seriously amazed by how advanced Fortran compilers are but so are C compilers).

PS : i'm glad you specifically excluded libs because i have a great deal of bad stuff to say about Fortran GUI libs. :)

I was doing some extensive mathematics with FORTRAN and C for a couple of years. From my own experience I can tell that FORTRAN is sometimes really better than C but not for its speed (one can make C perform as fast as FORTRAN by using appropriate coding style) but rather because of very well optimized libraries like LAPACK, and because of great parallelization. On my opinion, FORTRAN is really awkward to work with, and its advantages are not good enough to cancel that drawback, so now I am using C+GSL to do calculations.

I haven't heard that Fortan is significantly faster than C, but it might be conceivable tht in certain cases it would be faster. And the key is not in the language features that are present, but in those that (usually) absent.

An example are C pointers. C pointers are used pretty much everywhere, but the problem with pointers is that the compiler usually can't tell if they're pointing to the different parts of the same array.

For example if you wrote a strcpy routine that looked like this:

strcpy(char *d, const char* s)
{
  while(*d++ = *s++);
}

The compiler has to work under the assumption that the d and s might be overlapping arrays. So it can't perform an optimization that would produce different results when the arrays overlap. As you'd expect, this considerably restricts the kind of optimizations that can be performed.

[I should note that C99 has a "restrict" keyword that explictly tells the compilers that the pointers don't overlap. Also note that the Fortran too has pointers, with semantics different from those of C, but the pointers aren't ubiquitous as in C.]

But coming back to the C vs. Fortran issue, it is conceivable that a Fortran compiler is able to perform some optimizations that might not be possible for a (straightforwardly written) C program. So I wouldn't be too surprised by the claim. However, I do expect that the performance difference wouldn't be all that much. [~5-10%]

Using modern standards and compiler, no!

Some of the folks here have suggested that FORTRAN is faster because the compiler doesn't need to worry about aliasing (and hence can make more assumptions during optimisation). However, this has been dealt with in C since the C99 (I think) standard with the inclusion of the restrict keyword. Which basically tells the compiler, that within a give scope, the pointer is not aliased. Furthermore C enables proper pointer arithmetic, where things like aliasing can be very useful in terms of performance and resource allocation. Although I think more recent version of FORTRAN enable the use of "proper" pointers.

For modern implementations C general outperforms FORTRAN (although it is very fast too).

http://benchmarksgame.alioth.debian.org/u64q/fortran.html

EDIT:

A fair criticism of this seems to be that the benchmarking may be biased. Here is another source (relative to C) that puts result in more context:

http://julialang.org/benchmarks/

You can see that C typically outperforms Fortran in most instances (again see criticisms below that apply here too); as others have stated, benchmarking is an inexact science that can be easily loaded to favour one language over others. But it does put in context how Fortran and C have similar performance.

Fortran can handle array, especially multidimensional arrays, very conveniently. Slicing elements of multidimensional array in Fortran can be much easier than that in C/C++. C++ now has libraries can do the job, such as Boost or Eigen, but they are after all external libraries. In Fortran these functions are intrinsic.

Whether Fortran is faster or more convenient for developing mostly depends on the job you need to finish. As a scientific computation person for geophysics, I did most of computation in Fortran (I mean modern Fortran, >=F90).

This is more than somewhat subjective, because it gets into the quality of compilers and such more than anything else. However, to more directly answer your question, speaking from a language/compiler standpoint there is nothing about Fortran over C that is going to make it inherently faster or better than C. If you are doing heavy math operations, it will come down to the quality of the compiler, the skill of the programmer in each language and the intrinsic math support libraries that support those operations to ultimately determine which is going to be faster for a given implementation.

EDIT: Other people such as @Nils have raised the good point about the difference in the use of pointers in C and the possibility for aliasing that perhaps makes the most naive implementations slower in C. However, there are ways to deal with that in C99, via compiler optimization flags and/or in how the C is actually written. This is well covered in @Nils answer and the subsequent comments that follow on his answer.

Generally FORTRAN is slower than C. C can use hardware level pointers allowing the programmer to hand-optimize. FORTRAN (in most cases) doesn't have access to hardware memory addressing hacks. (VAX FORTRAN is another story.) I've used FORTRAN on and off since the '70's. (Really.)

However, starting in the 90's FORTRAN has evolved to include specific language constructs that can be optimized into inherently parallel algorithms that can really scream on a multi-core processor. For example, automatic Vectorizing allows multiple processors to handle each element in a vector of data concurrently. 16 processors -- 16 element vector -- processing takes 1/16th the time.

In C, you have to manage your own threads and design your algorithm carefully for multi-processing, and then use a bunch of API calls to make sure that the parallelism happens properly.

In FORTRAN, you only have to design your algorithm carefully for multi-processing. The compiler and run-time can handle the rest for you.

You can read a little about High Performance Fortran, but you find a lot of dead links. You're better off reading about Parallel Programming (like OpenMP.org) and how FORTRAN supports that.

The faster code is not really up to the language, is the compiler so you can see the ms-vb "compiler" that generates bloated, slower and redundant object code that is tied together inside an ".exe", but powerBasic generates too way better code. Object code made by a C and C++ compilers is generated in some phases (at least 2) but by design most Fortran compilers have at least 5 phases including high-level optimizations so by design Fortran will always have the capability to generate highly optimized code. So at the end is the compiler not the language you should ask for, the best compiler i know is the Intel Fortran Compiler because you can get it on LINUX and Windows and you can use VS as the IDE, if you're looking for a cheap tigh compiler you can always relay on OpenWatcom.

More info about this: http://ed-thelen.org/1401Project/1401-IBM-Systems-Journal-FORTRAN.html

Fortran has better I/O routines, e.g. the implied do facility gives flexibility that C's standard library can't match.

The Fortran compiler directly handles the more complex syntax involved, and as such syntax can't be easily reduced to argument passing form, C can't implement it efficiently.

There is nothing about the languages Fortran and C which makes one faster than the other for specific purposes. There are things about specific compilers for each of these languages which make some favorable for certain tasks more than others.

For many years, Fortran compilers existed which could do black magic to your numeric routines, making many important computations insanely fast. The contemporary C compilers couldn't do it as well. As a result, a number of great libraries of code grew in Fortran. If you want to use these well tested, mature, wonderful libraries, you break out the Fortran compiler.

My informal observations show that these days people code their heavy computational stuff in any old language, and if it takes a while they find time on some cheap compute cluster. Moore's Law makes fools of us all.

There is another item where Fortran is different than C - and potentially faster. Fortran has better optimization rules than C. In Fortran, the evaluation order of an expressions is not defined, which allows the compiler to optimize it - if one wants to force a certain order, one has to use parentheses. In C the order is much stricter, but with "-fast" options, they are more relaxed and "(...)" are also ignored. I think Fortran has a way which lies nicely in the middle. (Well, IEEE makes the live more difficult as certain evaluation-order changes require that no overflows occur, which either has to be ignored or hampers the evaluation).

Another area of smarter rules are complex numbers. Not only that it took until C 99 that C had them, also the rules govern them is better in Fortran; since the Fortran library of gfortran is partially written in C but implements the Fortran semantics, GCC gained the option (which can also be used with "normal" C programs):

-fcx-fortran-rules Complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there is no checking whether the result of a complex multiplication or division is "NaN + I*NaN", with an attempt to rescue the situation in that case.

The alias rules mentioned above is another bonus and also - at least in principle - the whole-array operations, which if taken properly into account by the optimizer of the compiler, can lead faster code. On the contra side are that certain operation take more time, e.g. if one does an assignment to an allocatable array, there are lots of checks necessary (reallocate? [Fortran 2003 feature], has the array strides, etc.), which make the simple operation more complex behind the scenes - and thus slower, but makes the language more powerful. On the other hand, the array operations with flexible bounds and strides makes it easier to write code - and the compiler is usually better optimizing code than a user.

In total, I think both C and Fortran are about equally fast; the choice should be more which language does one like more or whether using the whole-array operations of Fortran and its better portability are more useful -- or the better interfacing to system and graphical-user-interface libraries in C.

Most of the posts already present compelling arguments, so I will just add the proverbial 2 cents to a different aspect.

Being fortran faster or slower in terms of processing power in the end can have its importance, but if it takes 5 times more time to develop something in Fortran because:

  • it lacks any good library for tasks different from pure number crunching
  • it lack any decent tool for documentation and unit testing
  • it's a language with very low expressivity, skyrocketing the number of lines of code.
  • it has a very poor handling of strings
  • it has an inane amount of issues among different compilers and architectures driving you crazy.
  • it has a very poor IO strategy (READ/WRITE of sequential files. Yes, random access files exist but did you ever see them used?)
  • it does not encourage good development practices, modularization.
  • effective lack of a fully standard, fully compliant opensource compiler (both gfortran and g95 do not support everything)
  • very poor interoperability with C (mangling: one underscore, two underscores, no underscore, in general one underscore but two if there's another underscore. and just let not delve into COMMON blocks...)

Then the issue is irrelevant. If something is slow, most of the time you cannot improve it beyond a given limit. If you want something faster, change the algorithm. In the end, computer time is cheap. Human time is not. Value the choice that reduces human time. If it increases computer time, it's cost effective anyway.

Fortran traditionally doesn't set options such as -fp:strict (which ifort requires to enable some of the features in USE IEEE_arithmetic, a part of f2003 standard). Intel C++ also doesn't set -fp:strict as a default, but that is required for ERRNO handling, for example, and other C++ compilers don't make it convenient to turn off ERRNO or gain optimizations such as simd reduction. gcc and g++ have required me to set up Makefile to avoid using the dangerous combination -O3 -ffast-math -fopenmp -march=native. Other than these issues, this question about relative performance gets more nit-picky and dependent on local rules about choice of compilers and options.

ReferenceURL : https://stackoverflow.com/questions/146159/is-fortran-easier-to-optimize-than-c-for-heavy-calculations

반응형