[Python] What does <string>:2(__init__) have to do with mathematical computations?

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm in the process of writing some mathematical operations. Here's a sample program to give you an idea of what kind of thing I could be doing:

    from dataclasses import dataclass
    import random

    @dataclass
    class Point:
    x: float
    y: float

    @dataclass
    class Vector:
    a: Point
    b: Point
    def x(self, y): return self.a.x + (y - self.a.y) * (self.b.x - self.a.x) / (self.b.y - self.a.y)
    def y(self, x): return self.a.y + (x - self.a.x) * (self.b.y - self.a.y) / (self.b.x - self.a.x)

    def process(v: Vector):
    v.a.x = v.b.y

    for i in range(10 ** 7):
    process(Vector(Point(random.random(), random.random()), Point(random.random(), random.random())))


    It does not perform as fast as I'd like it to so I profile the script with python3 -m cProfile test.py, here's the first few lines of the output:

    ncalls tottime percall cumtime percall filename:lineno(function)
    9/1 0.001 0.000 239.400 239.400 {built-in method builtins.exec}
    1 130.752 130.752 239.400 239.400 test.py:1(<module>)
    40000000 54.230 0.000 54.230 0.000 {method 'random' of '_random.Random' objects}
    20000000 26.921 0.000 26.921 0.000 <string>:2(__init__)
    10000000 13.814 0.000 13.814 0.000 test.py:16(process)


    What is that <string>:2(__init__) doing there and why is it taking up so much time? Nowhere in my program did I mention strings.

    More generally, how would you advise to go about 2D vector/matrix processing in Python in the most performant way? I'll be doing thousands or maybe millions of simple algebraic calculations on 2D points which would be nothing in C but in Python does seem to require an approach.

    Note I'm running this in a VM therefore it's a bit sluggish. The OS is Ubuntu.

    Continue reading...

Compartilhe esta Página