论C++和Python运行效率
#include <stdio.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <GL/gl.h>
#include <vector>
#include <cmath>
// 物理参数
const float h = 3000.0f;
const float v0 = 200.0f;
const float g = 9.8f;
const int n = 30;
int main()
{
// 初始化GLFW
if (!glfwInit())
{
return -1;
}
// 创建窗口 (OpenGL ES 1.1)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
GLFWwindow *window = glfwCreateWindow(800, 600, "窗口标题", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// 计算点
std::vector<glm::vec2> points;
float tmax = std::sqrt(2 * h / g);
float delta = tmax / (n - 1);
for (int i = 0; i < n; ++i)
{
float t = i * delta;
float xt = v0 * t;
float yt = h - 0.5f * g * t * t;
points.push_back(glm::vec2(xt, yt));
}
// 主渲染循环
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
float aspect = static_cast<float>(width) / height;
// 设置视口
glViewport(0, 0, width, height);
// 清除屏幕
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // 白色背景
glClear(GL_COLOR_BUFFER_BIT);
// 设置正交投影
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float orthoWidth = h * aspect; // 保持宽高比
glOrtho(0.0f, orthoWidth, 0.0f, h, -1.0f, 1.0f); // 使用glOrtho
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// 绘制网格
glColor4f(0.8f, 0.8f, 0.8f, 1.0f); // 灰色网格
glLineWidth(1.0f);
// 垂直线
for (float x = 0; x <= orthoWidth; x += 500.0f)
{
glBegin(GL_LINES);
glVertex2f(x, 0.0f);
glVertex2f(x, h);
glEnd();
}
// 水平线
for (float y = 0; y <= h; y += 500.0f)
{
glBegin(GL_LINES);
glVertex2f(0.0f, y);
glVertex2f(orthoWidth, y);
glEnd();
}
// 绘制弹道点
glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // 红色点
glPointSize(5.0f);
glBegin(GL_POINTS);
for (const auto &p : points)
{
glVertex2f(p.x, p.y);
}
glEnd();
// 交换缓冲区和事件处理
glfwSwapBuffers(window);
glfwPollEvents();
}
// 清理资源
glfwTerminate();
return 0;
}
且看python
import matplotlib.pyplot as plt
h,v0,g=3000,200,9.8
t,n=0,30
h=3000
tmax=(2*h/9)**0.5
delta=tmax/(n-1)
while t<=tmax:
xt=v0*t
yt=h-1/2*g*t**2
plt.plot(xt,yt,'ro')
t=t=delta
plt.grid('on')
plt.axis([0,5000,0,h])
plt.show()

浙公网安备 33010602011771号