fix time module bug pocketpy.h

There was a problem with the implementation of the time() function, and I couldn't get the correct time, so I replaced the original implementation with std::chrono::system_clock:now().
This commit is contained in:
小染 2023-05-24 13:27:38 +08:00 committed by GitHub
parent 0befc0139f
commit c9492355f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1015,17 +1015,15 @@ inline void init_builtins(VM* _vm) {
inline void add_module_time(VM* vm){ inline void add_module_time(VM* vm){
PyObject* mod = vm->new_module("time"); PyObject* mod = vm->new_module("time");
vm->bind_func<0>(mod, "time", [](VM* vm, ArgsView args) { vm->bind_func<0>(mod, "time", [](VM* vm, ArgsView args) {
auto now = std::chrono::high_resolution_clock::now(); auto now = std::chrono::system_clock::now();
return VAR(std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count() / 1000000.0); return VAR(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() / 1000.);
}); });
vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) { vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
f64 seconds = VAR_F(args[0]); int64_t now = std::chrono::system_clock::now().time_since_epoch().count();
auto begin = std::chrono::high_resolution_clock::now(); int64_t end = now + 1000'0000 * vm->num_to_float(args[0]);
while(true){ while (now < end) {
auto now = std::chrono::high_resolution_clock::now(); now = std::chrono::system_clock::now().time_since_epoch().count();
f64 elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now - begin).count() / 1000000.0;
if(elapsed >= seconds) break;
} }
return vm->None; return vm->None;
}); });