In my QGIS plugin I'm adding some different layers to the QGIS canvas with a uri connection to my Postgres database, adding one layer takes no time, hence adding 20 layers takes some time. So I tried to understand what consumed the time by adding some t=time.time(), this is part of my code:

host = self.dbhost
port = self.dbport
dbname = self.dbname
username = self.dbuser
password = self.dbpass
t0 = time.time()
## Adds a PostGIS table to the map
uri = QgsDataSourceUri()
uri.setConnection(str(host), str(port), str(dbname), str(username), str(password))
uri.setDataSource(str(schema), str(table), str(geom_col), filter_text, 'field_row_id')
t1 = time.time()
vlayer = QgsVectorLayer(uri.uri(), str(extra_name) + str(table), 'postgres')
t2 = time.time()
if not vlayer.isValid():
    QMessageBox.information(None, 'Error', 'Layer not loaded correctly, Connection:\n' + str(uri.uri()))
print('DBfunc: setting uri con {u} s, creating layer from uri {s}, checking it {t1}'.format(u=round(t1-t0,3),s=round(t2-t1,3),t1=round(time.time()-t2,2)))

So the log clearly showed that setting the Uri connection (the code until t1 took no time (less than 0.001 s), checking if the layer was valid took no time (less than 0.001 s), hence the code line creating the QgsVectorLayer took approximate 0.5 sec to execute. Is here any improvements to be made? (using QGIS3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.