Google V8 如日中天, 凭借 Chrome 和 NodeJS 两款应用, 在开发者中有极好的口碑
先下载 v8 编译生成若干所需的库文件
# 项目主页
https://code.google.com/p/v8/
# 编译安装, 得先安装 gjt, depot_tools , 参见以下链接, 在此略过
* https://code.google.com/p/v8-wiki/wiki/BuildingWithGYP
# 参考资料, 可能需
* https://developers.google.com/v8/embed
* https://developers.google.com/v8/get_started
* https://code.google.com/p/v8-wiki/wiki/BuildingWithGYP
# 测试程序 makefile.am如下, 测试环境为 macbook air, osx 10.10.3, Darwin Kernel Version 14.3.0 ,
V8Test_SOURCES = v8test.cpp
V8Test_CPPFLAGS = -I$(top_srcdir)/third_party/v8 -I$(top_srcdir)/util -pthread -lrt -stdlib=libstdc++ -std=c++11
V8Test_LDFLAGS = -L/workspace/cpp/v8/xcodebuild/Release -L$(top_srcdir)/util -stdlib=libstdc++ -std=c++11
V8Test_LDADD = -lv8_base -lv8_libbase -lv8_snapshot -lv8_libplatform -licuuc -licui18n -licudata
还是和上一篇一样的 javascript arraysort.js:
function random_str()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 8; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var array = new Array();
for ( var i = 0; i < 10000; i++)
{
array[array.length] = random_str();
}
debug_trace("begin sort and reverse array which length=" + array.length );
array.sort();
array.reverse();
debug_trace("done, first element=" + array[0]+ ", " + "last element=" + array[array.length-1] );
现在由 V8 来执行, 看看测试结果如何
废话不多说, 先上源码 v8test.cpp, 根据 V8 自带的 shell.cc 改写而来
#include "include/v8.h"
#include "include/libplatform/libplatform.h"
using namespace v8;
long long current_timestamp(char arrTimeStr[TIME_FMT_LEN]) {
struct timeval tv;
struct tm* ptm;
char time_string[40];
gettimeofday(&tv, NULL); // get current time
if (arrTimeStr) {
ptm = localtime(&tv.tv_sec);
/* Format the date and time, down to a single second. */
strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm);
/* Compute milliseconds from microseconds. */
//snprintf(char * restrict str, size_t size, const char * restrict format,
snprintf(arrTimeStr, TIME_FMT_LEN, "%s.%06d", time_string, tv.tv_usec);
}
long long total_us = tv.tv_sec * 1000000LL + tv.tv_usec ; // caculate milliseconds
// printf("milliseconds: %lld\n", milliseconds);
return total_us;
}
// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
return *value ? *value : "";
}
void debug_trace(const v8::FunctionCallbackInfo& args)
{
if (args.Length() > 0) {
char szTimeStr[TIME_FMT_LEN] = { '\0' };
current_timestamp(szTimeStr);
v8::String::Utf8Value str(args[0]);
const char* cstr = ToCString(str);
printf("[%s] %s\n", szTimeStr, cstr);
}
}
v8::Handle ReadFile(v8::Isolate* isolate, const char* name) {
FILE* file = fopen(name, "rb");
if (file == NULL) return v8::Handle();
fseek(file, 0, SEEK_END);
int size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (int i = 0; i < size;) {
int read = static_cast(fread(&chars[i], 1, size - i, file));
i += read;
}
fclose(file);
v8::Handle result =
v8::String::NewFromUtf8(isolate, chars, v8::String::kNormalString, size);
delete[] chars;
return result;
}
v8::Handle CreateShellContext(v8::Isolate* isolate) {
// Create a template for the global object.
v8::Handle global = v8::ObjectTemplate::New(isolate);
// Bind the global 'print' function to the C++ Print callback.
global->Set(v8::String::NewFromUtf8(isolate, "debug_trace"),
v8::FunctionTemplate::New(isolate, debug_trace));
return v8::Context::New(isolate, NULL, global);
}
void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
v8::HandleScope handle_scope(isolate);
v8::String::Utf8Value exception(try_catch->Exception());
const char* exception_string = ToCString(exception);
v8::Handle message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
fprintf(stderr, "%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber();
fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
// Print line of source code.
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceline_string = ToCString(sourceline);
fprintf(stderr, "%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
fprintf(stderr, " ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
fprintf(stderr, "^");
}
fprintf(stderr, "\n");
v8::String::Utf8Value stack_trace(try_catch->StackTrace());
if (stack_trace.length() > 0) {
const char* stack_trace_string = ToCString(stack_trace);
fprintf(stderr, "%s\n", stack_trace_string);
}
}
}
// Executes a string within the current v8 context.
bool ExecuteString(v8::Isolate* isolate,
v8::Handle source,
v8::Handle name,
bool print_result,
bool report_exceptions) {
v8::HandleScope handle_scope(isolate);
v8::TryCatch try_catch;
v8::ScriptOrigin origin(name);
v8::Handle script = v8::Script::Compile(source, &origin);
if (script.IsEmpty()) {
// Print errors that happened during compilation.
if (report_exceptions)
ReportException(isolate, &try_catch);
return false;
} else {
v8::Handle result = script->Run();
if (result.IsEmpty()) {
assert(try_catch.HasCaught());
// Print errors that happened during execution.
if (report_exceptions)
ReportException(isolate, &try_catch);
return false;
} else {
assert(!try_catch.HasCaught());
if (print_result && !result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
v8::String::Utf8Value str(result);
const char* cstr = ToCString(str);
printf("%s\n", cstr);
}
return true;
}
}
}
int main(int argc, char* argv[]) {
// Initialize V8.
V8::InitializeICU();
Platform* platform = platform::CreateDefaultPlatform();
V8::InitializePlatform(platform);
V8::Initialize();
// Create a new Isolate and make it the current one.
Isolate* isolate = Isolate::New();
{
Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
HandleScope handle_scope(isolate);
// Create a new context.
v8::Handle context = CreateShellContext(isolate);
if (context.IsEmpty()) {
fprintf(stderr, "Error creating context\n");
return 1;
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
Local source;
Local filename;
if (argc > 1) {
filename = String::NewFromUtf8(isolate, argv[1]);
source = ReadFile(isolate, argv[1]);
} else {
source = String::NewFromUtf8(isolate, "'Hello' + ', World!'");
filename = String::NewFromUtf8(isolate, "nofile");
}
long long begin_time = current_timestamp(NULL);
ExecuteString(isolate, source,filename, false, true);
long long end_time = current_timestamp(NULL);
printf("calling costs %lld microseconds\n", end_time - begin_time);
}
// Dispose the isolate and tear down V8.
isolate->Dispose();
V8::Dispose();
V8::ShutdownPlatform();
delete platform;
return 0;
}
SpiderMonkey 执行此 JS 文件共花费了 46.781 ms, 其中一万个元素的字符串数组排序反转花费了 3 ms 不到的时间
$ ./test/SpiderMonkeyTest ./test/arraysort.js
[2015-05-10 08:22:20.246747] begin sort and reverse array which length=10000
[2015-05-10 08:22:20.249263] done, first element=zzvJWaQw, last element=00BpApzs
calling costs 46781 microseconds
V8 执行此 JS 文件共花费了 22.326 ms, 其中一万个元素的字符串数组排序反转花费了约 9 ms
$ ./test/V8Test ./test/arraysort.js
[2015-05-10 08:22:34.324314] begin sort and reverse array which length=10000
[2015-05-10 08:22:34.337588] done, first element=zzmBlrhz, last element=00G00Ssm
calling costs 22326 microseconds
总时间 V8 果然名不虚传, 总的执行比 spidermonkey 快了一倍多, 但有趣的是在内部的字符串数组排序反转所花费的时间方面 SpiderMonkey 反而遥遥领先, 有待研究