Database queries, model checking, and graph problems can be succinctly specified with relational rules, and then expressed with a rule-based language such as Datalog. This paper develops a method for automatic generation of efficient programs from the rules. In parallel, the formulas for the guaranteed worst-case running time and space complexity of this implementation can also be derived directly from the rules. The approach is neither an evaluation nor a rewriting method. Rather, it is a direct translation of the rules into a standard imperative programming language. The process starts with a fixed-point specification that is transformed into a loop for handling new facts, with one per iteration. The loop is optimized with efficient incremental operations, which in turn are supported with customized data structures. Selected graph-theoretical problems illustrate well the methodology of this rigorously presented paper.