Qual é o custo de uma falha de cache L1?
Editar: Para fins de referência (se alguém se depara com esta questão), Igor Ostrovsky escreveu umótimo post sobre falhas de cache. Ele discute vários problemas diferentes e mostra números de exemplo.End Edit
Fiz alguns testes<long story goes here>
e estou querendo saber se uma diferença de desempenho é devido a falta de memória cache. O código a seguir demonstra o problema e o resume à parte de tempo crítico. O código a seguir possui alguns loops que visitam a memória em ordem aleatória e, em seguida, na ordem crescente de endereços.
Eu corri em uma máquina XP (compilada com VS2005: cl / O2) e em uma caixa Linux (gcc –Os). Ambos produziram tempos semelhantes. Esses tempos estão em milissegundos. Acredito que todos os loops estão em execução e não estão otimizados (caso contrário, seriam executados “instantaneamente”).
*** Testing 20000 nodes Total Ordered Time: 888.822899 Total Random Time: 2155.846268
Esses números fazem sentido? A diferença é principalmente devido a erros de cache L1 ou algo mais está acontecendo também? Existem 20.000 ^ 2 acessos de memória e se todos forem um erro de cache, isto é, cerca de 3,2 nanossegundos por falta. A máquina XP (P4) que eu testei é de 3.2GHz e eu suspeito (mas não sei) tem um cache L1 de 32KB e 512KB L2. Com 20.000 entradas (80KB), presumo que não haja um número significativo de erros de L2. Então isso seria(3.2*10^9 cycles/second) * 3.2*10^-9 seconds/miss) = 10.1 cycles/miss
. Isso parece alto para mim. Talvez não seja, ou talvez minha matemática seja ruim. Eu tentei medir falhas de cache com VTune, mas eu tenho um BSOD. E agora não consigo conectá-lo ao servidor de licenças (grrrr).
typedef struct stItem
{
long lData;
//char acPad[20];
} LIST_NODE;
#if defined( WIN32 )
void StartTimer( LONGLONG *pt1 )
{
QueryPerformanceCounter( (LARGE_INTEGER*)pt1 );
}
void StopTimer( LONGLONG t1, double *pdMS )
{
LONGLONG t2, llFreq;
QueryPerformanceCounter( (LARGE_INTEGER*)&t2 );
QueryPerformanceFrequency( (LARGE_INTEGER*)&llFreq );
*pdMS = ((double)( t2 - t1 ) / (double)llFreq) * 1000.0;
}
#else
// doesn't need 64-bit integer in this case
void StartTimer( LONGLONG *pt1 )
{
// Just use clock(), this test doesn't need higher resolution
*pt1 = clock();
}
void StopTimer( LONGLONG t1, double *pdMS )
{
LONGLONG t2 = clock();
*pdMS = (double)( t2 - t1 ) / ( CLOCKS_PER_SEC / 1000 );
}
#endif
long longrand()
{
#if defined( WIN32 )
// Stupid cheesy way to make sure it is not just a 16-bit rand value
return ( rand() << 16 ) | rand();
#else
return rand();
#endif
}
// get random value in the given range
int randint( int m, int n )
{
int ret = longrand() % ( n - m + 1 );
return ret + m;
}
// I think I got this out of Programming Pearls (Bentley).
void ShuffleArray
(
long *plShuffle, // (O) return array of "randomly" ordered integers
long lNumItems // (I) length of array
)
{
long i;
long j;
long t;
for ( i = 0; i < lNumItems; i++ )
plShuffle[i] = i;
for ( i = 0; i < lNumItems; i++ )
{
j = randint( i, lNumItems - 1 );
t = plShuffle[i];
plShuffle[i] = plShuffle[j];
plShuffle[j] = t;
}
}
int main( int argc, char* argv[] )
{
long *plDataValues;
LIST_NODE *pstNodes;
long lNumItems = 20000;
long i, j;
LONGLONG t1; // for timing
double dms;
if ( argc > 1 && atoi(argv[1]) > 0 )
lNumItems = atoi( argv[1] );
printf( "\n\n*** Testing %u nodes\n", lNumItems );
srand( (unsigned int)time( 0 ));
// allocate the nodes as one single chunk of memory
pstNodes = (LIST_NODE*)malloc( lNumItems * sizeof( LIST_NODE ));
assert( pstNodes != NULL );
// Create an array that gives the access order for the nodes
plDataValues = (long*)malloc( lNumItems * sizeof( long ));
assert( plDataValues != NULL );
// Access the data in order
for ( i = 0; i < lNumItems; i++ )
plDataValues[i] = i;
StartTimer( &t1 );
// Loop through and access the memory a bunch of times
for ( j = 0; j < lNumItems; j++ )
{
for ( i = 0; i < lNumItems; i++ )
{
pstNodes[plDataValues[i]].lData = i * j;
}
}
StopTimer( t1, &dms );
printf( "Total Ordered Time: %f\n", dms );
// now access the array positions in a "random" order
ShuffleArray( plDataValues, lNumItems );
StartTimer( &t1 );
for ( j = 0; j < lNumItems; j++ )
{
for ( i = 0; i < lNumItems; i++ )
{
pstNodes[plDataValues[i]].lData = i * j;
}
}
StopTimer( t1, &dms );
printf( "Total Random Time: %f\n", dms );
}