Statistics - QueryStat

The Database object has a thread-local property local_stats which contains query execution statistics. The property value is a dict, where keys are SQL queries and values are instances of the QueryStat class. A QueryStat object has the following attributes:

class QueryStat

  • sql

    The text of SQL query

  • db_count

    The number of times this query was sent to the database

  • cache_count

    The number of times the query result was taken directly from the db_session() cache (for cases when a query was called repeatedly inside the same db_session())

  • min_time

    The minimum time required for database to execute the query

  • max_time

    The maximum time required for database to execute the query

  • avg_time

    The average time required for database to execute the query

  • sum_time

    Total time spent (is equal to avg_time * db_count)

Pony keeps all statistics separately for each thread. If you want to see the aggregated statistics for all threads then you need to call the merge_local_stats() method. See also: local_stats(), global_stats().

Example:

  1. query_stats = sorted(db.local_stats.values(),
  2. reverse=True, key=attrgetter('sum_time'))
  3. for qs in query_stats:
  4. print(qs.sum_time, qs.db_count, qs.sql)