簡體   English   中英

在高性能計算中,更好的做法是:將數據結構傳遞給一個函數或一組變量?

[英]What is better practise in high-performance computing: passing a struct of data into a function or a set of variables?

想象一下,我有一個結構,其中包含一組描述一個對象的變量,該對象在我的情況下是一個網格。 我想知道,如果我有一個僅使用網格子集的函數,下面的computational_kernel函數的兩個變體是否存在性能差異。 內核是相同的,只是傳遞結構的內核必須在完成大量計算之前從結構中提取itotjtotktot

struct Grid
{
    int itot;
    int jtot;
    int ktot;

    int not_used_in_kernel1;
    int not_used_in_kernel2;
    int not_used_in_kernel3;
    int not_used_in_kernel4;
}
Grid grid;

// Code that initializes the grid values...

// Variant 1
computational_kernel(double* array1, double* array2,
                     const int itot, const int jtot, const int ktot);

// Variant 2
computational_kernel(double* array1, double* array2,
                     const Grid& grid);

我認為通過結構體可以更好地保持代碼。 如果將新字段添加到網格中,則只需更改功能。 但是傳遞一組變量,您將不得不更改函數以及對該函數的每次調用。

如果computational_kernel是一個在內部執行大量工作並且被調用幾次的函數,則這兩個版本之間的差異是無限的。 第二個版本僅具有解引用3個值的額外開銷,而其余版本則相同,因此您大概必須在調用第一個版本之前進行此類反引用。

出於緊湊性原因,我肯定會使用第二種形式:如果要定義面向對象的數據結構,請以這種方式使用(更好的封裝)。

我要說的是,像在第二個變體中那樣傳遞對結構的引用可能會更有效。 在第一個變體中,調用者將需要將3個int變量壓入堆棧,而在第二個變體中,其只需壓入一個對結構的引用(指針)並在其中進行操作。 如果要傳遞三個以上的變量,則對性能的影響當然更大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM