在大整数数组中查找子数组 我想用C++在嵌入式CPU上计算任务栈的高水印。 不幸的是,操作系统没有提供这样的方法
任务堆栈本身是一个整数数组。未命名堆栈包含0xCDCD作为值。由于0xCDCDCD可能是一个有效值,因此我希望找到终止序列的第一次出现重复4次 所以我在一个大整数数组中搜索一个整数(子)数组。 由于我必须暂停任务,这种方法应该非常有效 我尝试了非常天真的方法在大整数数组中查找子数组 我想用C++在嵌入式CPU上计算任务栈的高水印。 不幸的是,操作系统没有提供这样的方法,c++,arrays,find,C++,Arrays,Find,任务堆栈本身是一个整数数组。未命名堆栈包含0xCDCD作为值。由于0xCDCDCD可能是一个有效值,因此我希望找到终止序列的第一次出现重复4次 所以我在一个大整数数组中搜索一个整数(子)数组。 由于我必须暂停任务,这种方法应该非常有效 我尝试了非常天真的方法 #define STACK_DEFAULT_VALUE 0xCDCDCDCD ///< marking for an empty stack element #define N_EMPTY_SUCCESSORS
#define STACK_DEFAULT_VALUE 0xCDCDCDCD ///< marking for an empty stack element
#define N_EMPTY_SUCCESSORS 4 ///< Min number of succeedeing stack elements before we assume we found the high watermark
int Get_Task_Stack_High_Watermark(const int* const pStack, const int stack_size)
{
int res = 0;
for(int i = 0;i<stack_size;i++)
{
if(*(pStack[i] != STACK_DEFAULT_VALUE))
{
//this part of the stack was allready in use
continue;
}
bool res = true;
//we found a stack mark => check if the next stack elements are unused as well
for(int j = i; j<i+N_EMPTY_SUCCESSORS; j++)
{
if(j>= stack_size)
{
//we reached the end of the stsck!
return 0;
}
if(*(pStack[j] != STACK_DEFAULT_VALUE))
{
//this is not the end of the stack
res = false;
}
}
if(res)
{
//this is the end of the (used) stack
//calculate remaining stack size
res = stack_size - i;
break;
}
}
return res;
}
#为空堆栈元素定义堆栈默认值0xCDCDCDCD//<标记
#在我们假设找到高水位线之前,定义N_EMPTY_继任者4//
但是我想知道有没有更快的方法
您有什么建议吗?您可以使用计数器跟踪一行中特殊值的数量:
#define STACK_DEFAULT_VALUE 0xCDCDCDCD ///< marking for an empty stack element
#define N_EMPTY_SUCCESSORS 4 ///< Min number of succeedeing stack elements before we assume we found the high watermark
int Get_Task_Stack_High_Watermark(const int* const pStack, const int stack_size)
{
int consecutiveEmpties = 0;
for(int i = 0;i < stack_size; i++)
{
if(pStack[i] == STACK_DEFAULT_VALUE)
{
consecutiveEmpties++;
if(consecutiveEmpties == N_EMPTY_SUCCESSORS)
{
return i - 4;
}
}
else
{
consecutiveEmpties = 0;
}
}
return stack_size;
}
#为空堆栈元素定义堆栈_默认值0xcdcd///<标记
#在我们假设找到高水位线之前,定义N_EMPTY_继任者4//
或者如果你真的不在乎可读性:
int Get_Task_Stack_High_Watermark_2(const int* const pStack, const int stack_size)
{
int consecutiveEmpties = 0;
for (int i = 0; i < stack_size; i++)
{
if ((consecutiveEmpties = (consecutiveEmpties + 1) * (pStack[i] == STACK_DEFAULT_VALUE)) == N_EMPTY_SUCCESSORS)
{
return i - 4;
}
}
return stack_size;
}
int Get_Task_Stack_High_Watermark_2(常量int*常量pStack,常量int Stack_size)
{
int连续空数=0;
对于(int i=0;i
第二个版本要快一点(visual studio的发布模式)那么这一切归结为查找给定值的连续出现次数吗?归结为查找第一个出现次数n个连续出现次数:)您可以通过首先查找
0xcdcd
,简单地使测试短路,然后查看下面的项目4插槽是否也是0xcdcd
。如果不是,那么您可以跳过整个块,因为不需要进一步的测试。您的意思是使用std::find()?用更大的示例可视化。如果要查看100个连续条目是否为0xcdcdcd
,该怎么办?您将找到第一个,然后立即向下查找100个插槽,查看该项目是否也是0xcdcd
。如果不是,则可以跳过整个块,因为它不能满足标准,即,在测试的第100个块之后,转到下一个块。使用您的方法,您将浪费时间检查块i、i+1、i+2、i+3等。稍后,您将发现块i+99(例如)不是0xCDCDCDCD
。