1

In a qgis 2.0 plugin for windows, I calculate length and update a field with the values. It works, but takes a lot of time. Execution for this part only takes about ten minutes. Can anyone suggest anything to speed things up?

def calculatelength(self):
    idx = self.resLayer.fieldNameIndex('Longueur')
    caps = self.resLayer.dataProvider().capabilities()
    features = self.resLayer.getFeatures()
    for feature in features:
        if caps & QgsVectorDataProvider.ChangeAttributeValues:
            fid = feature.id()
            flen = feature.geometry().length()
            attrs = {idx : flen}
            self.resLayer.dataProvider().changeAttributeValues({fid : attrs})
2
  • How many features?
    – Nathan W
    Oct 2, 2014 at 6:40
  • @NathanW approximately 6000 line features
    – user25976
    Oct 3, 2014 at 18:32

1 Answer 1

1

I think the call to resLayer.dataProvider().changeAttributeValues has too much overhead in terms of disk access+writing, etc.. Try storing all your edits in a dictionary(or list) and then doing the editing in edit mode all in one go.

def calculatelength(self):
    idx = self.resLayer.fieldNameIndex('Longueur')
    caps = self.resLayer.dataProvider().capabilities()
    features = self.resLayer.getFeatures()
    edits = {}
    for feature in features:
        if caps & QgsVectorDataProvider.ChangeAttributeValues:
            fid = feature.id()
            flen = feature.geometry().length()
            edits[fid] = flen

    self.resLayer.startEditing()
    for fid in edits:
        self.resLayer.changeAttributeValue(fid, idx, edits[fid])
    self.resLayer.commitChanges()
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.