ModularM
Modular16mo ago
21 replies
DayDayUp

How to improve the performance of formatting output

I wrote a piece of scientific simulation code as shown below:
    fn run(inout self) raises -> None:
        with open(self.output_path, "w") as f:
            var out: String = "location,velocity,acceleration\n"
            for _ in range(1, self.numsteps + 1):
                self.velocity = self.velocity + self.acceleration * self.deltaT / 2
                self.location = self.location + self.velocity * self.deltaT
                self.acceleration = -1 * self.location
                out += str(self.location) + "," + str(self.velocity) + "," + str(self.acceleration) + "\n"
            
            f.write(out)

Its performance is much lower than that of C/C++ and Swift. I know I’m a rookie at coding… As I’ve checked, the lagging part is: out += str(self.location) + "," + str(self.velocity) + "," + str(self.acceleration) + "\n". Are there any good ways to optimize the data output?
Was this page helpful?