Dijkstra algorithm optimization/caching

后端 未结 3 905

I have the following Dijkstra algorithm with 3 input variables (start, stop and time). It takes about 0.5-1s to complete. My hosting provider says it\'s using too muc

3条回答
  •  眼角桃花
    2020-12-20 04:23

    it's using too much resources

    Which resource? (CPU? Memory? Network bandwidth? I/O load on the database server?)

    while (true) {       
        $result=mysql_query("SELECT route_id, next_stop FROM db_stop_times WHERE stop_id = $activeNode", $connection);
    

    If I am reading this right you are doing a database call for every node in every pathfinding attempt. Each of these calls will block for a little while waiting for the response from the database. Even if you have a fast database, that's bound to take a couple milliseconds (unless the database is running on the same server as your code). So I'd venture the guess that most of your execution time is spent waiting for replies from the database.

    Moreover, should your database lack proper indexes, each query could do a full table scan ...

    The solution is straightforward: Load db_stop_times into memory at application startup, and use that in-memory representation when resolving neighbour nodes.

    Edit: Yes, an index on stop_id would be a proper index for this query. As for practical caching, I don't know PHP, but with something like Java (or C#, or C++, or even C) I'd use a representation of the form

    class Node {
        Link[] links;
    }
    
    class Link {
        int time;
        Node destination;
    }
    

    that would be a bit faster than memcached, but assumes you can comfortably fit the entire table in main memory. If you can't do that, I'd use a caching system like memcached.

提交回复
热议问题