# Most efficient way to count # of intrcutions in a module ?

I need to count the total number of instructions in a given module.
The only way I found is using the obvious double iteration as seen
below. Is there any more efficient way to achieve this ? I don't like
the fact that simple calculation like that has performance of o(F*B)
(# of functions * # of blocks per function)

unsigned int calcSize(Module* mod)
{
unsigned int size = 0;
for (Module::iterator f = mod->begin(), fe = mod->end(); f != fe; ++f)
for (Function::iterator b = f->begin(), be = f->end(); b != be; ++b)
{
BasicBlock* bb = (BasicBlock*) b;
size+=bb->getInstList().size();
}
return size;
}

Gabi wrote:

I need to count the total number of instructions in a given module.
The only way I found is using the obvious double iteration as seen
below. Is there any more efficient way to achieve this ? I don't like
the fact that simple calculation like that has performance of o(F*B)
(# of functions * # of blocks per function)

If you just want to know given a .bc file, you can run 'opt -instcount -stats' which is a pass that does pretty much what you wrote, except that it does a per-instruction breakdown which means that it will be a little slower.

unsigned int calcSize(Module* mod)
{
unsigned int size = 0;
for (Module::iterator f = mod->begin(), fe = mod->end(); f != fe; ++f)
for (Function::iterator b = f->begin(), be = f->end(); b != be; ++b)
{
BasicBlock* bb = (BasicBlock*) b;
size+=bb->getInstList().size();
}
return size;
}

Your implementation isn't actually O(n^2) if that's what you're worried about. It's just O(n) where n is the # instructions in the whole program. You're doing it as efficiently as possible.

Also, you should be able to write 'size += b->getInstList().size()' without the explicit cast.

Nick