Loop interchange

In compiler theory, loop interchange is the process of exchanging the order of two iteration variables used by a nested loop. The variable used in the inner loop switches to the outer loop, and vice versa. It is often done to ensure that the elements of a multi-dimensional array are accessed in the order in which they are present in memory, improving locality of reference.

For example, in the code fragment:

for j from 0 to 20
  for i from 0 to 10
    a[i,j] = i + j

loop interchange would result in:

for i from 0 to 10
  for j from 0 to 20
    a[i,j] = i + j

On occasion, such a transformation may create opportunities to further optimize, such as automatic vectorization of the array assignments.

The utility of loop interchange

Illustration of row- and column-major order

The major purpose of loop interchange is to take advantage of the CPU cache when accessing array elements. When a processor accesses an array element for the first time, it will retrieve an entire block of data from memory to cache. That block is likely to have many more consecutive elements after the first one, so on the next array element access, it will be brought directly from cache (which is faster than getting it from slow main memory). Cache misses occur if the contiguously accessed array elements within the loop come from a different cache block, and loop interchange can help prevent this. The effectiveness of loop interchange depends on and must be considered in light of the cache model used by the underlying hardware and the array model used by the compiler.

In C programming language, array elements in the same row are stored consecutively in memory (a[1,1], a[1,2], a[1,3]) ‒ in row-major order. On the other hand, FORTRAN programs store array elements from the same column together (a[1,1], a[2,1], a[3,1]), using column-major. Thus the order of two iteration variables in the first example is suitable for a C program while the second example is better for FORTRAN.[1] Optimizing compilers can detect the improper ordering by programmers and interchange the order to achieve better cache performance.

Caveat

Loop interchange may lead to worse performance because cache performance is only part of the story. Take the following example:

 do i = 1, 10000
   do j = 1, 1000
     a[i] = a[i] + b[j,i] * c[i]
   end do
 end do

Loop interchange on this example can improve the cache performance of accessing b(j,i), but it will ruin the reuse of a(i) and c(i) in the inner loop, as it introduces two extra loads (for a(i) and for c(i)) and one extra store (for a(i)) during each iteration. As a result, the overall performance may be degraded after loop interchange.

Safety

It is not always safe to exchange the iteration variables due to dependencies between statements for the order in which they must execute. To determine whether a compiler can safely interchange loops, dependence analysis is required.

See also

References

  1. ^ "Loop interchange" (PDF). Parallel Programming Guide for HP-UX Systems. HP. August 2003.

Further reading

Read other articles:

Extinct Indo-European language of northeast Italy This article is about the extinct Venetic language. For the modern day Romance language, see Venetian language. For the anti-crime operation, see Operation Venetic. For other uses, see Veneti (disambiguation). VeneticNative toItalyRegionVenetoEthnicityAdriatic VenetiEraattested 6th–1st century BCE[1]Language familyIndo-European Italic (?) orpara-Celtic (?)[2]VeneticWriting systemOld Italic (Venetic alphabet)Language code...

 

Dieser Artikel behandelt die linken und autonomen Strömungen. Zur Zeitschrift siehe antifa (Zeitschrift). Zur Ablehnung und Bekämpfung von Faschismus siehe Antifaschismus. Dieser Artikel oder Absatz stellt die Situation in Deutschland dar. Bitte hilf uns dabei, die Situation in anderen Staaten zu schildern. Logo mit roter und schwarzer Fahne Antifa (Kopfwort von Antifaschistische Aktion) wird von den Wissenschaftlichen Diensten des Deutschen Bundestages als ein „Oberbegriff für verschied...

 

МазеMazaye Країна  Франція Регіон Овернь-Рона-Альпи  Департамент Пюї-де-Дом  Округ Іссуар Кантон Рошфор-Монтань Код INSEE 63219 Поштові індекси 63230 Координати 45°47′11″ пн. ш. 2°51′37″ сх. д.H G O Висота 676 - 958 м.н.р.м. Площа 21,73 км² Населення 707 (01-2020[1]) Густота 32,81 ос./км

Public school in Hampstead, London, This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: University College School – news · newspapers · books · scholar · JSTOR (September 2019) (Learn how and when to remove this template message) University College SchoolLocationFrognal, London, NW3EnglandCoordinates51°33′12...

 

كامبو   لمعانٍ أخرى، طالع كامبو (توضيح). هذا المقال جزء من سلسلة عنالطب البديل والعلوم الزائفة معلومات عامة طب بديل طب بيطري بديل الدجل (الخداع الطبي) تاريخ الطب البديل تاريخ الطب العلوم الزائفة مناهضة العلم شكوكية شكوكية علمية المركز القومي للطب البديل والتكميلي مصطلح

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يوليو 2020) سانتا سيسيليا دو سول    علم شعار   الإحداثيات 28°09′43″S 51°55′30″W / 28.161944444444°S 51.925°W / -28.161944444444; -51.925  [1] تقسيم إداري  البلد البرازي...

For the state pageant affiliated with Miss USA, see Miss Colorado USA. Beauty pageant competition Miss ColoradoFormation1926TypeScholarship competitionMembership Miss AmericaWebsiteOfficial website Miss Colorado, Madison Marsh in Greeley, Colorado; July 2023 The Miss Colorado competition is the pageant that selects the representative for the state of Colorado in the Miss America pageant. Colorado has won the Miss America crown on three occasions. Madison Marsh of Colorado Springs, Colorado wa...

 

Declaration of Independence for the Republic of Kosovo Politics of Kosovo Constitution and law Executive President Vjosa Osmani Prime Minister Albin Kurti Second Kurti cabinet Government Legislature Assembly Chairman: Glauk Konjufca Judiciary Constitutional Court Kosovo Judicial Council Administrative divisions Districts Municipalities Recent elections Presidential: 201120162021 Parliamentary: 201420172019 Local: 2009201320172021 Referendums: 19912012 Political parties PDKLDKAAKSLSVVAKR Forei...

 

Village in East Azerbaijan province, Iran Village in East Azerbaijan, IranTaleb Khan Persian: طالبخانVillageTaleb KhanCoordinates: 37°23′27″N 46°12′17″E / 37.39083°N 46.20472°E / 37.39083; 46.20472[1]Country IranProvinceEast AzerbaijanCountyMaraghehDistrictCentralRural DistrictSarajuy-ye GharbiPopulation (2016)[2] • Total2,848Time zoneUTC+3:30 (IRST) Taleb Khan (Persian: طالبخان, also Romanized as Ţāleb ...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (يناير 2020) تتناول هذه المقالة التسلسل الزمني للحرب الإسبانية المغربية (وتسمى أيضًا الحرب الإسبانية المغربية (1859-1860) ...

 

2021 filmThe Legend of the UndergroundOfficial posterDirected by Nneka Onuorah Giselle Bailey Produced by Giselle Bailey Nneka Onourah Stephen Bailey CinematographyStephen BaileyEdited byRabab Haj YahyaProductioncompanies HBO Documentary Films Get Lifted Film Company Nala Films Distributed byHBORelease dates June 10, 2021 (2021-06-10) (Tribeca) June 29, 2021 (2021-06-29) (United States) Running time100 minutes[1]Countries United States Nigeria Lan...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يونيو 2021) إزا ديك هاكيت معلومات شخصية الميلاد 15 مارس 1967 (56 سنة)  مواطنة الولايات المتحدة  الأب فيليب ك. ديك  الحياة العملية المهنة منتجة أفلام،  وكاتِبة  ال...

This article is an orphan, as no other articles link to it. Please introduce links to this page from related articles; try the Find link tool for suggestions. (January 2016) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Surya Sen Park – news · newspapers · books · scholar · JSTOR (July 2013) (Learn how and...

 

Argentine fashion model (born 1991) Flo GennaroGennaro at Custo Barcelona Spring 2009 showBorn (1991-01-09) January 9, 1991 (age 32)[1]Rosario, Argentina[2]Modeling informationHeight6 ft; 1.83 mHair colorLight BrownEye colorBrown Flo Gennaro (born January 9, 1991[1] in Rosario, Santa Fe) is an Argentine fashion model. She has modeled for Ann Demeulemeester, Chaiken, Christian Dior, Costello Tagliapietra, Doo.Ri, Lanvin, Louis Vuitton, Marni, and Nina Ric...

 

Romanian football club Football clubUniversitatea GalațiFull nameFotbal Club Universitatea GalațiNickname(s)Panterele Negre[1] (The Black Panthers)Gălățencele(The Women from Galați)Short nameU GalațiFounded2015; 8 years ago (2015)GroundSiderurgistulCapacity6,000ChairmanGabriel CălinescuManagersGabriel CălinescuAlexandru CaracașLeagueLiga I2019–20Liga I, 2nd Home colours Away colours Fotbal Club Universitatea Galați, commonly known as Universitatea Galaț...

Small tablet with a curse written on it from the Greco-Roman world Eyguieres curse tablet A curse tablet (Latin: tabella defixionis, defixio; Greek: κατάδεσμος, romanized: katadesmos) is a small tablet with a curse written on it from the Greco-Roman world. Its name originated from the Greek and Latin words for pierce[1] and bind. The tablets were used to ask the gods, place spirits, or the deceased to perform an action on a person or object, or otherwise compel the subj...

 

АО «Трансмашхолдинг» Электропоезд Иволга в сборочном цехе Тверского вагоностроительного завода, 6 ноября 2019 Тип Акционерное общество Основание 2002 Расположение  Россия: Москва Ключевые фигуры Кирилл Липа (генеральный директор) Отрасль Транспортное машиностроение Со...

 

العلاقات الأوزبكستانية الصينية أوزبكستان الصين   أوزبكستان   الصين تعديل مصدري - تعديل   العلاقات الأوزبكستانية الصينية هي العلاقات الثنائية التي تجمع بين أوزبكستان والصين.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وج...

Wied Musa BatteryBatterija ta' Wied MusaMellieħa, Malta Wied Musa Battery as viewed from the seaMap of Wied Musa Battery as it is todayCoordinates35°59′12.7″N 14°20′31.4″E / 35.986861°N 14.342056°E / 35.986861; 14.342056TypeArtillery batterySite informationOwnerGovernment of MaltaOpen tothe publicNoConditionGun platform intactBlockhouse largely destroyedSite historyBuilt1714–1716Built byOrder of Saint JohnMaterialsLimestone Wied Musa Batte...

 

Sirih Selembar daun sirih Klasifikasi ilmiah Kerajaan: Plantae Ordo: Piperales Famili: Piperaceae Genus: Piper Spesies: P. betle Nama binomial Piper betleL. Sirih adalah tanaman asli dari Indonesia yang tumbuh merambat atau bersandar pada batang pohon lain.[1] Sirih dikenal dalam masing-masing bahasa dengan nama yang khas, yaitu: suruh (Jawa), lu'at (Bahasa Ma'anyan),sireh (Melayu), bido (Ternate), base (Bali), dan amo (Ambon).[2] Sebagai budaya daun dan buahnya biasa dik...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!