Home > Uncategorized > Fast Python VTK import

Fast Python VTK import

he Python VTK module is long to import because it load all the native VTK libraries which most of the time you won’t need. With VTK already in memory (disk cache):

$ time python -c "import vtk"

real 0m2.951s
user 0m2.964s
sys 0m1.860s

Here is a way to make it fast:

import sys
import types

class FastVTKLoader(object):
def __init__(self, modules):
self.modules = modules

def imp(self):
if not sys.meta_path:
sys.meta_path.append(self)
else:
sys.meta_path[0] = self
import vtk
sys.meta_path.remove(self)
return vtk

def load_module(self, name):
return types.ModuleType(name)

def find_module(self, name, path=None):
if name.startswith("vtk.vtk") and not name.endswith("Python"):
vm = name[7:]
if vm not in self.modules:
return self

vtk = FastVTKLoader(["CommonCore", "CommonDataModel", "IOXML", "FiltersExtraction"]).imp()
$ time python myvtkloader.py

real 0m0.077s
user 0m0.076s
sys 0m0.000s

Inspired by this Stackoverflow answer.

Advertisements
Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: