我正在为自己的乐趣做基准测试!我已经用许多编程语言编写了一部分代码,并使用ab对其进行基准测试,以查看哪些更快,更多。我知道这个方法可能不那么有效,并且不能用作使用某些方法的明显方法,但对于我自己的信息,我这样做。我想知道的另一个因素是在每种语言中编写相同的样本是多么容易/困难。我用Python / Python(asyncio),Haskell,Go,Kotlin和D编写了代码。我将D端口设置为比Go更快(或至少速度相等)。但不幸的是我的D代码比Go慢得多。在这里我把oth代码,请帮助我为什么代码没有按预期快。或者我的期望完全错了吗?
import cbor;
import std.array : appender;
import std.format;
import std.json;
import vibe.vibe;
struct Location
{
float latitude;
float longitude;
float altitude;
float bearing;
}
RedisClient redis;
void main()
{
auto settings = new HTTPServerSettings;
redis = connectRedis("localhost", 6379);
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, &hello);
logInfo("Please open http://127.0.0.1:8080/ in your browser.");
runApplication();
}
void hello(HTTPServerRequest req, HTTPServerResponse res)
{
if (req.path == "/locations") {
immutable auto data = req.json;
immutable auto loc = deserializeJson!Location(data);
auto buffer = appender!(ubyte[])();
encodeCborAggregate!(Flag!"WithFieldName".yes)(buffer, loc);
auto db = redis.getDatabase(0);
db.set("Vehicle", cast(string) buffer.data);
res.writeBody("Ok");
}
}
这是Go
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/context"
)
import "github.com/go-redis/redis"
import (
"bytes"
"github.com/2tvenom/cbor"
)
type Location struct {
Latitude float32 `json:"latitude"`
Longitude float32 `json:"longitude"`
Altitude float32 `json:"altitude"`
Bearing float32 `json:"bearing"`
}
func main() {
app := iris.New()
client := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
app.Post("/locations", func(ctx context.Context) {
var loc Location
ctx.ReadJSON(&loc)
var buffTest bytes.Buffer
encoder := cbor.NewEncoder(&buffTest)
encoder.Marshal(loc)
client.Set("vehicle", buffTest.Bytes(), 0)
client.Close()
ctx.Writef("ok")
})
app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8"))
}
使用ab,Go结果约为4200 req / sec,而D约为2800 req / sec!
答案 0 :(得分:6)
您不只是对Go vs D进行基准测试。您还可以将您对特定选择的非标准Go和D库进行基准测试:cbor
,vibe
,iris
等等。您正在对特定实施进行基准测试which can easily vary by 1000x in performance。
有了这么多变量,原始基准数对于比较两种语言的性能来说毫无意义。这些第三方库中的任何一个都可能导致性能问题。真的,你只是比较那两个特定的程序。这是尝试比较跨语言的琐碎程序的核心问题:变量太多了。
您可以使用performance profiling减少某些变量的影响;在Go中,这将是go tool pprof
。这将告诉您正在调用的函数和行数以及需要多少资源。有了它,您可以找到瓶颈,代码中占用大量资源的地方,并在那里集中优化工作。
在为每个版本进行配置文件和优化轮次时,您将更接近于比较真实的优化实现。或者您将更好地了解每种语言和库的有效性,以及它们不能做什么。
比较语言的问题很大程度上受特定问题和特定程序员的影响。 X程序员总是认为X是最好的语言,不是因为X是最好的语言,而是因为X编程人员在用X编写时是最好的,并且可能选择了他们感觉舒服的问题。因此,有许多项目可以为每种语言提供最佳实施方案。
立刻想到的是The Computer Language Benchmarks Game。他们做Go,但不是D.也许你可以添加它?